Share on Google+Share on Google+

Java read file line by line

In this section, you will learn how to read a file line by line.

Java read file line by line

In this section, you will learn how to read a file line by line.

Java has provide several classes for file manipulation. Here we are going to read a file line by line. For reading text from a file it's better to use a Reader class instead of a InputStream class since Reader classes have the purpose of reading textual input.
In the given example, we have simply create a BufferedReader object and start reading from the file line by line until the readLine() method of BufferedReader class returns null, which indicates the end of the file.



Where there is will, there is a way.

Here is the code:


public class ReadFile {
	public static void main(String[] args) throws Exception {

		File f = new File("C:/Hello.txt");
		if (!f.exists() && f.length() < 0) {
			System.out.println("The specified file does not exist");
		} else {
			FileReader fr = new FileReader(f);
			BufferedReader reader = new BufferedReader(fr);
			String st = "";
			while ((st = reader.readLine()) != null) {

In this above code, the BufferedReader class is used to read text from a file line by line using it's readLine method.


Posted on: January 25, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.