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