0

I am thinking up a way to get around the whole bad habit that is using an infinite loop to read in objects. My algorithm involves iteratively checking

if (FileInputStream("myFile.ser").available() != 0) and then deserialize the next object. Otherwise, I would close the file.

I want to know if this is the correct way to go about this.

I have read this question's answers: May the FileInputStream.available foolish me? and don't know if, by empty, they mean that the read pointer is at the end-of-file.

In other words, Could I trust FileInputStream.available() to check how much data is still available for reading from the file?

Community
  • 1
  • 1
Mike Warren
  • 3,796
  • 5
  • 47
  • 99

1 Answers1

2

No, you should never use InputStream.available() for anything. the method is too loosely defined (and implemented) to mean anything.

why is an infinite loop a "bad habit"?

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
  • It is a bad habit if you are a multilingual programmer. For example, if you move into a language like C++, you have to be careful. There, it could cause the machine to crash! I did come up with an alternative (that will cost O(33 bytes) of data : save the number of records to a binary file like this: '1.) Save the number of bytes the number of records will span to the binary file' '2.) Save the number byte-by-byte to the binary file' This way, you know how many bytes the number spans and can read it in as an array of int, and manipulate it to the actual number! This is good for 2^32-1 objects. – Mike Warren Apr 18 '13 at 21:31
  • The algorithm works for Math.pow(2,32) - 1 objects (an insane number of objects; the serialization thing might fall apart before this many is reached!!) – Mike Warren Apr 18 '13 at 21:34
  • @MikeWarren - infinite loops don't work any differently in c++ than they do in java. – jtahlborn Apr 18 '13 at 21:49