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


Page:    1 2 >

Reading a file line-by-line in JavaSW is quite easy. The BufferedReader class allows you to read an input stream line-by-line via its readLine() method. This is illustrated below in the ReadStringFromFileLineByLine class.

ReadStringFromFileLineByLine.java

package test;

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

public class ReadStringFromFileLineByLine {

	public static void main(String[] args) {
		try {
			File file = new File("test.txt");
			FileReader fileReader = new FileReader(file);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			StringBuffer stringBuffer = new StringBuffer();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				stringBuffer.append(line);
				stringBuffer.append("\n");
			}
			fileReader.close();
			System.out.println("Contents of file:");
			System.out.println(stringBuffer.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

In this class, the test.txt file is read via a FileReader, which in turn is fed to a BufferedReader. The BufferedReader is read line-by-line, and each line is appended to a StringBuffer, followed by a linefeed. The contents of the StringBuffer are then output to the console.

The test.txt file is shown below.

test.txt

this is
a test
file

(Continued on page 2)

Page:    1 2 >