1
DataInputStream dis = new DataInputStream(con.getInputStream());
while(dis.available() > 0 {
  long mydata = dis.readLong();
   // read more data for a record
  ...
   workOnOneRecord();    
}

I read multiple binary variable size records of data and EOF would happen at the end of one set of data. I understand this available() is wrong, if data arrives in chunks? (Could happen that there's more data pending, sender has not yet closed the stream, etc. ?)

This is for reading over a network connection, there's no filesize or similar, known in advance.

I'd like to reserve the EOFException to an error case, running into EOF unexpectedly. Is there something like while (! dis.EOF() ) { ... } before the next read would return EOF ?

datafiddler
  • 1,755
  • 3
  • 17
  • 30
  • 2
    There is no difference between expected and unexpected EOF unless you have a *basis* for your expectation, such as a record count that is transmitted ahead of the records. Otherwise you are stuck with `EOFExveptuon` in both cases. And even if you have an expectation, there's no guarantee it will be met: things can change. The sender may be cut off before it has sent all the data. Or it may send more. There's really no reason to overcomplicate this. Just read until `EOFException` is caught. – user207421 Sep 08 '16 at 12:34
  • 2
    I wish `available()` had some warning on it, so people wouldn't keep using it. – Kayaman Sep 08 '16 at 12:39
  • @Kayaman Indeed. Today I disovered that the Javadoc for `returns` is actually wrong: it states that it returns 0 at end of stream. Well, it does, but it can return it any other time as well. – user207421 Sep 08 '16 at 12:56
  • @EJP: "Just read until EOFException is caught" is too simple, but thanks for confirmation. I will try/catch read the first element of a record separately. This really is "expected" to happen in normal operation. Of course, EOF has to be considered for any readData. But further handling is very different then. Exception is preferred over checking for a basic `is.read()` returning -1 – datafiddler Sep 08 '16 at 14:08

0 Answers0