How to sort Text file content in Java

(131 Views)


Problem Statement

Write a java program or method to sort a text file containing some records. The program should take a text file containing some records as input parameter, then sort the records either alphabetically and write the sorted content in another text file.

Steps to Sort the txt file content:

  1. Read contents of the text file.
  2. Store the contents in an ArrayList.
  3. Sort the ArrayList with Collection.sort() method.
  4. Write this sorted content to another text file.

Read contents of the text file:

We create a BufferedReader object and pass our file to it in the form of FileReader object.

FileReader fr = new FileReader("path to file"); BufferedReader reader = new BufferedReader(fr);

Store the contents in an ArrayList:

We don't know the length of content in the text file, so we need a dynamic size data structure and ArrayList fulfills this purpose.

We read the file line by line and store add it in our ArrayList.

ArrayList<String> str = new ArrayList<>(); String line = ""; while((line=reader.readLine())!=null){ str.add(line); }

Sort the arrayList:

Java Collections provide an easy way to sort the data of any Collection by using sort() method. By default sort() method is used to sort the elements present in the list in ascending order. sort() method is found in java.util.Collections.

Collections.sort(str);

Write the contents to another text file:

FileWriter writer = new FileWriter("newFile"); for(String s: str){ writer.write(s); writer.write("\r\n"); }

Full Program to sort contents of text file:

import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; public class Example{ public static void main(String[] args) throws IOException{ BufferedReader reader = new BufferedReader(new FileReader("filePath")); ArrayList<String> str = new ArrayList<>(); String line = ""; while((line=reader.readLine())!=null){ str.add(line); } reader.close(); Collections.sort(str); FileWriter writer = new FileWriter("new file"); for(String s: str){ writer.write(s); writer.write("\r\n"); } writer.close(); } }

Input

Output

Solution Worked 0 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote



Comments



Search