Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort records in a text file using Java?

Some amendment of the data in txt file. I have tried the suggested code but Im not successfully write it again in the txt file with this format.I've tried the collection.sort but it write the data in long line.

My txt file contain these data:

Monday
Jessica  Run      20mins
Alba     Walk     20mins
Amy      Jogging  40mins
Bobby    Run      10mins
Tuesday
Mess     Run      20mins
Alba     Walk     20mins
Christy  Jogging  40mins
Bobby    Run      10mins

How can I sort those data in ascending order and store it again in txt file after sorting?

Monday
Alba     Walk     20mins
Amy      Jogging  40mins
Bobby    Run      10mins
Jessica  Run      20mins
Tuesday
Alba     Walk     20mins
Bobby    Run      10 mins
Christy  Jogging  40mins
Mess     Run      20mins
Jessica  Run      20mins
like image 212
Jessy Avatar asked Apr 11 '09 22:04

Jessy


People also ask

How do you sort data in a text file?

Although there's no straightforward way to sort a text file, we can achieve the same net result by doing the following: 1) Use the FileSystemObject to read the file into memory; 2) Sort the file alphabetically in memory; 3) Replace the existing contents of the file with the sorted data we have in memory.

How do you sort collection of elements in Java?

sort() method is present in java. util. Collections class. It is used to sort the elements present in the specified list of Collection in ascending order.

How do you sort data alphabetically in Java?

Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.


1 Answers

Here's something I came up with:

import java.io.*;
import java.util.*;

public class Sort {

    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new FileReader("fileToRead"));
        Map<String, String> map=new TreeMap<String, String>();
        String line="";
        while((line=reader.readLine())!=null){
            map.put(getField(line),line);
        }
        reader.close();
        FileWriter writer = new FileWriter("fileToWrite");
        for(String val : map.values()){
            writer.write(val);  
            writer.write('\n');
        }
        writer.close();
    }

    private static String getField(String line) {
        return line.split(" ")[0];//extract value you want to sort on
    }
}
like image 148
Peter Dolberg Avatar answered Oct 07 '22 00:10

Peter Dolberg