Java check 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.

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.

Ads