How do I get a List of the lines in a File using Commons IO and alphabetize them?
Author: Deron Eriksson
Description: This Java tutorial describes how to get a List of the lines in a File and alphabetize them.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

In another tutorial, we saw how we could get a List of the lines of a File very easily using the readLines() method of the FilesUtils class of the ApacheSW Commons IOS library. We can very easily alphabetize the List of lines with a call to Collections.sort(), since a List is a Collection. The ReadListOfLinesFromFileAndAlphabetize class demonstrates this.

package test;

import java.util.Collections;
import java.util.List;


public class ReadListOfLinesFromFileAndAlphabetize {

	public static void main(String[] args) {
		try {
			File file = new File("test.txt");
			List<String> lines = FileUtils.readLines(file);


			for (String line : lines) {
				System.out.println("line:" + line);

		} catch (IOException e) {

The test.txt file is shown here:


this is
a test
of commons io

Executing ReadListOfLinesFromFileAndAlphabetize with test.txt generates the following console output:

line:a test
line:of commons io
line:this is

Note that Collections.sort() will treat uppercase and lowercase characters as not being equal when it performs a sort. To ignore case (and treat uppercase/lowercase the same), you can create a Comparator for strings and call toLowerCase() or toUppercase() when you compare them to 'equalize' the cases.