Tuesday, May 10, 2011

Java: read a text file line by line

This class reads a text file line by line and echos the contents to standard out.
Here we have used BufferedReader to do this.
import java.io.*;

public static String readFile(String fileName)
// nested initialization,
// or in design pattern jargon, decorate FileInputStream with
// BufferedInputStream.
BufferedReader in = new BufferedReader(new FileReader(fileName));
try {
// read file line by line
String line = in.readLine();
while (line != null) {
line = in.readLine();
finally {
// always close input stream
private static void printLine(String line) {

No comments:

Post a Comment