How do I read a String from a File using Commons IO?
Author: Deron Eriksson
Description: This Java tutorial describes an easy way to read a String from a file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The ApacheSW Commons IOS library has some great tools for working with files, such as the FileUtils class, which makes it very easy to read a String from a File. We can see an example of this below:

ReadStringFromFile.java

package test;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class ReadStringFromFile {

	public static void main(String[] args) throws IOException {
		File file = new File("test.txt");
		String string = FileUtils.readFileToString(file);
		System.out.println("Read in: " + string);
	}
}

The test.txt file is shown here:

test.txt

This is
a test

If we execute the ReadStringFromFile class with the test.txt file, it generates the following output to the console:

Read in: This is
a test

If you need to use a particular encoding, you can specify it via

FileUtils.readFileToString(File file, String encoding)