How do I alphabetically sort the lines of a file?
Author: Deron Eriksson
Description: This Java tutorial describes how to alphabetically sort the lines of a file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


A text file can be read line-by-line with a BufferedReader. To sort these lines, we can read them into a List and run a Collections.sort() on the List.

The AlphabeticallySortLinesOfTextInFile class demonstrates this. It reads in a text file line-by-line and adds each line to an ArrayList. When this is done, it sorts the list with Collections.sort(). To display the results, it outputs all the lines to an output file using a PrintWriter and FileWriter.

AlphabeticallySortLinesOfTextInFile.java

package test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class AlphabeticallySortLinesOfTextInFile {

	public static void main(String[] args) throws Exception {

		String inputFile = "input.txt";
		String outputFile = "output.txt";

		FileReader fileReader = new FileReader(inputFile);
		BufferedReader bufferedReader = new BufferedReader(fileReader);
		String inputLine;
		List<String> lineList = new ArrayList<String>();
		while ((inputLine = bufferedReader.readLine()) != null) {
			lineList.add(inputLine);
		}
		fileReader.close();

		Collections.sort(lineList);

		FileWriter fileWriter = new FileWriter(outputFile);
		PrintWriter out = new PrintWriter(fileWriter);
		for (String outputLine : lineList) {
			out.println(outputLine);
		}
		out.flush();
		out.close();
		fileWriter.close();

	}
}

The input file is shown here.

input.txt

this is a 
file that we
are using to test

If we execute AlphabeticallySortLinesOfTextInFile, it generates the output.txt file shown below.

output.txt

are using to test
file that we
this is a