Program to Sort all contents of file by line in java


Let’s say c:/myFile.txt looks like this >
you are
learning file
io from
javaMadeSoEasy a

Write a Program to Sort all contents of file by line and write it back in file in java, such that after execution of program file must look like this -

io from
javaMadeSoEasy a
learning file
you are



Logic >
1) Read file in String, and store each String in ArrayList
2) Sort ArrayList
3) Now, write sorted content in file


Program to Sort all contents of file by line and write it back in file in java  >

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortContentsByLinesInFile {
   public static void main(String[] args) {
         
          String fileName ="c:/myFile.txt";
         
         
          try {
                 //1) Read file in String, and store each String in ArrayList
                 FileReader fr = new FileReader(fileName);
                 BufferedReader br = new BufferedReader(fr);
                
                 List<String> l=new ArrayList<String>();
                 String str;
                
                 while((str = br.readLine()) != null){
                       l.add(str);
                 }
                 br.close();
                
                 //By now, String fileDataInString contains all the data of file
                
                
                 //2) Sort ArrayList
                 Collections.sort(l);
                 System.out.print("Display sorted list > ");
                 //Display sorted list
                 System.out.println(l);
                
                 //3) Now, write sorted content in file
                 FileWriter fw = new FileWriter(fileName);
                 BufferedWriter bw = new BufferedWriter(fw);
                 for(String s: l){
                       bw.write(s);
                       bw.write("\n");
                 }
                
                 bw.close();
                 System.out.println("\nSorted content has been written in file");
                
                
          } catch (FileNotFoundException e) {
                 e.printStackTrace();
          } catch (IOException e) {
                 e.printStackTrace();
          }
         
   }
}
/*OUTPUT
Display sorted list > [io from , javaMadeSoEasy a, learning file , you are ]
Sorted content has been written in file
*/



RELATED LINKS>

Create File using createNewFile() method in java file IO


Copy a file in java 2 in ways


Program to Write BYTE data type in file using DataOutputStream and Read BYTE from file using DataInputStream - java file IO


Find current directory or current path in java


No comments:

Post a Comment