Search code examples
javafileeofexception

Reading from binary file returns -1 without throwing EOFException


I am trying to read one byte integers from a file. The integers are read correctly however the process keeps reading the integer '-1' without throwing an EOF exception.

This is how I write the integers into the file. I read 4 byte integers from class1.dat and put those which are below 256 in output1.dat as 1 byte integers.

FileInputStream fis = new FileInputStream("D:\\class1.dat");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
FileOutputStream fos = new FileOutputStream("D:\\output1.dat");
DataOutputStream dos = new DataOutputStream(fos);

try
{
     while(true) 
     {
         number = dis.readInt();
         System.out.println("Integer read : " + number);

         if(number < 256)
             dos.write(number);

     }
}
catch(EOFException e)
{
      dis.close();
      dos.close();
}

This is how i read the 1 byte integers from output1.dat.

DataInputStream dis = new DataInputStream(new FileInputStream("D:\\output1.dat"));


try
{
      int number;

      System.out.println("File with < 256");

      while(true)
      {
            number = dis.read();
            System.out.println("Number =  "  + number);
      }

}
catch(EOFException e)
{
      dis.close();
}

Why doesn't EOFexception get thrown?


Solution

  • No EOFexception is thrown because you use the read method from DataInputStream which is actually inherited from FilterInputStream.

    And the doc here: https://docs.oracle.com/javase/7/docs/api/java/io/FilterInputStream.html#read() says

    Returns: the next byte of data, or -1 if the end of the stream is reached.

    No Exception is thrown when you reach the end of the stream.

    You may want to use the method readByte instead which throws an EOFException when the input stream has reached the end.