How do I read a String from a File?
Author: Deron Eriksson
Description: This Java tutorial describes how to read a String from a File.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1

Page:    1 2 >

Reading a String from a File is usually slightly more complicated that writing a String to a File, but not that much so. A typical method is to read a file using a FileReader object in blocks of character arrays via a loop and to append these blocks to a StringBuffer object, and when all this is done, to convert the StringBuffer to a String via StringBuffer's toString method.

This technique is illustrated in the class below.

package test;


public class ReadStringFromFile1 {

	public static void main(String[] args) {
		try {
			File file = new File("test1.txt");
			FileReader fileReader = new FileReader(file);
			StringBuffer stringBuffer = new StringBuffer();
			int numCharsRead;
			char[] charArray = new char[1024];
			while ((numCharsRead = > 0) {
				stringBuffer.append(charArray, 0, numCharsRead);
			System.out.println("Contents of file:");
		} catch (IOException e) {


ReadStringFromFile1 is shown in action in the screen capture from EclipseSW shown below:

Execution of ReadStringFromFile1

(Continued on page 2)

Page:    1 2 >