Home Tutorial Java Core Files Java check end of file

 
 

Share on Google+Share on Google+
Java check end of file
Posted on: April 14, 2006 at 12:00 AM
Advertisement
In this section, you will learn how to check that the file has been read till the end of file.

Java check end of file

In this section, you will learn how to check that the file has been read till the end of file.

Data has been read one by one from the file. The loop is used to continually read the file until there are no more data. This  indicates the end of file or eof condition. It depends on the InputStream or Reader object. If you are using readLine() method of BufferedReader, it returns null on the next read after the last data is read off the stream. If you are using read(byte[], int,int ) of FileInputstream, it returns -1 when there is no more data to read.

In the given example, we have used FileReader and BufferedReader class to read the file till the end of the file.

Here is the code:

import java.io.*;

public class FileEOF {
	public static void main(String[] args) throws Exception {
		FileReader reader = new FileReader("C:/file.txt");
		BufferedReader br = new BufferedReader(reader);
		String str = "";
		while ((str = br.readLine()) != null) {
			System.out.println(str);
		}
		br.close();
	}
}

Output:

Hello World

All glitters are not gold.
Truth is better than facts.
A man is not old until regrets take the place of dreams.

Advertisement

Related Tags for Java check end of file:


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: April 14, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com