Home Tutorial Java Core Files Java read file line by line

 
 

Share on Google+Share on Google+
Java read file line by line
Posted on: January 25, 2011 at 12:00 AM
Advertisement
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.

hello.txt:

Hello,

Where there is will, there is a way.

Here is the code:


import java.io.*;

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) {
				System.out.println(st);
			}
		}
	}
}

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

Advertisement

Related Tags for Java read file line by line:


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.

Posted on: January 25, 2011

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com