java.io.EOFException when try to read from a socket

Yusuf1494 picture Yusuf1494 · Jul 10, 2013 · Viewed 46.5k times · Source

i don't know why java.io.EOFException appear. i want to write a file after i get binary stream from server.

Here's my code

inputStream = new DataInputStream(new BufferedInputStream(connection.getInputStream()));
FileOutputStream fos = new FileOutputStream("D:/Apendo API resumable download.txt");

byte b = inputStream.readByte();
while(b != -1){
        fos.write(b);
        b = inputStream.readByte();                       
       }
fos.close();

Stack trace

java.io.EOFException
at java.io.DataInputStream.readByte(DataInputStream.java:267)
at HttpRequestJSON.JSONRequest.sendRequest(JSONRequest.java:64)
at HttpRequestJSON.Main.main(Main.java:56)

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Jul 10, 2013

DataInputStream.readByte API does not say it return -1 on EOS, it says

Returns:the next byte of this input stream as a signed 8-bit byte.

Throws: EOFException - if this input stream has reached the end.

It assumes that when working withh DataInputStream.readByte we know how many bytes are left in the stream. Otherwise we can use EOFException as an indicator of EOS.

BTW If you use read() you will get -1 on EOS without EOFException