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) {
printLine(line);
line = in.readLine();
}
}
finally {
// always close input stream
in.close();
}
}
private static void printLine(String line) {
System.out.println(line);
}

No comments:

Post a Comment

Chitika