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 ReadStringFromFile1.java class below.

ReadStringFromFile1.java

package test;

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

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 = fileReader.read(charArray)) > 0) {
				stringBuffer.append(charArray, 0, numCharsRead);
			}
			fileReader.close();
			System.out.println("Contents of file:");
			System.out.println(stringBuffer.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

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

Execution of ReadStringFromFile1

(Continued on page 2)

Page:    1 2 >