Text File Sort

Description: Takes the path to a text file used for input, sorts it and then writes it out to another text file. The input and output files can be the same file path. Requires: java.io package for the BufferedReader/Writer/ and FileReader/Writer classes. Also needs java.util package for the Collections/Arraylist classes.
Tested Platform: Java SE 19, Windows 10
Language: Java
// Takes an input file path and sorts it, then writes it to the output file path.
// Throws an exception if there is a problem reading or writing.
    
public static void sortFile(String inputFilePath, String outputFilePath) throws IOException {
    // Holds all the lines of our file and will be sorted afterwards.
    ArrayList<String> lines = new ArrayList<String>();
    String line = "";
        
    // Read each line, add it to our ArrayList
    BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
    while ((line = reader.readLine()) != null) {
        lines.add(line);
    }
        
    reader.close();
        
    Collections.sort(lines);
        
    // Open output file and write all the lines.
    // Use system line separator
        
    BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath));
    for (String str : lines) {
        writer.write(str + System.getProperty("line.separator"));
    }
        
    writer.close();
}

Posted: March 20, 2023

Return to the snippets listing