Question

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)
Was it helpful?

Solution

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

OTHER TIPS

From the DataInputStream Javadoc:

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way.

I'm not sure whether you need that, but you can decide for yourself. In general, if you're just downloading data and writing to a file, you won't need it - just stick with the BufferedInputStream.

The readByte() method reads one byte (hence the name) and it will throw an EOFException when the stream reaches the end before reading all the bytes. It might sound a bit confusing, but the exception is thrown reading input, not writing the file. It is, in fact, the only way to determine whether the DataInputStream has ended.

But once again, consider using just the BufferedInputStream, as it is probably all you need.

You have already read the byte then why are you again reading it in the while? Plus your check at while is not correct, you wont get -1 for DIS.readByte. Try using read().

It depends when you use client - server implementation and client is "always up" and socket is keeping whole time.

if socket connection is up and you use for example ObjectInputStream so "EOFException" will appear when client close socket (socket.close) or "java.net.SocketException: Connection" reset will apper when socket.close() isnt check at finally for sure...

But if you keep client and socket connection up ObjectInputStream.readObject() will stay and listen what is what you want in this scenario. and yes when you call only read() you will get -1 and if client is killed and you are handling for one client one thread at server you will only get -1 and thread will live foreever (if you dont kill it manualy or kill whole server)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top