Java – How to sort records in a text file using Java

filejavasortingtext-files

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

Best Answer

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
    }
}