What value does read() method return when it reaches the end of a file in java?


The read() method of the input stream classes reads the contents of the given file byte by byte and returns the ASCII value of the read byte in integer form. While reading the file if it reaches the end of the file this method returns -1.

Example

Assume we have a text file (sample.txt) in the current directory with a simple text saying “Hello welcome”. Following Java program reads the contents of the file byte by byte using the read() method and prints the integer value returned for each byte.

Since we are not checking for end of the file, the read() method reaches the end and the last integer of the output will be -1.

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class EndOfFileExample {
   public static void main(String[] args) {
      try{
         File file = new File("sample.txt");
         DataInputStream inputStream = new DataInputStream(new FileInputStream(file));
         System.out.println(file.length());
         for(int i=0; i<=file.length();i++) {
            int num = inputStream.read();
            System.out.println(num);
         }
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}

Output

13
72
101
108
108
111
32
119
101
108
99
111
109
101
-1

Updated on: 30-Jul-2019

920 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements