Mazzy
Mazzy

Reputation: 14229

Reading from a binary file object

I have to read a series of object from a binary file.

I use:

ObjectOutputStream obj = new ObjectOutputStream(new FileInputStream(fame));

obj.readObject(p);

where p is a reference to an object I had created. How can I read the entire file until the end?

I can use:

while(p!=null){}

?

Upvotes: 0

Views: 9959

Answers (5)

George Covrig
George Covrig

Reputation: 21

Boolean i = true;
while(i) {
    try {
        System.out.println(reader.readObject());
    } catch(Exception e) {
        i = false;
        System.out.println("Dead end");
    }
}

Upvotes: 0

James Clark
James Clark

Reputation: 1821

Let's assume you meant ObjectInputStream and p = obj.readObject().

I would do something like this: (this is wrong, see EDIT below)

FileInputStream fstream = new FileInputStream(fileName);
try {
  ObjectInputStream ostream = new ObjectInputStream(fstream);
  while (ostream.available() > 0) {
    Object obj = ostream.readObject();
    // do something with obj
  }
} finally {
  fstream.close();
}

EDIT

I take it back! EJP rightly points out that the use of available() is incorrect here. I think the fixed code might be:

FileInputStream fstream = new FileInputStream(fileName);
try {
  ObjectInputStream ostream = new ObjectInputStream(fstream);
  while (true) {
    Object obj;
    try {
      obj = ostream.readObject();
    } catch (EOFException e) {
      break;
    }
    // do something with obj
  }
} finally {
  fstream.close();
}

Although the documentation for readObject() doesn't explicitly say that EOFException is thrown at the end of the stream, it seems to be implied and may be the only way to detect the end of the stream.

Another option if you control the code that wrote the stream would be to write an object count at the beginning, or a flag after each object indicating whether the previous object was the final one.

Upvotes: 1

user207421
user207421

Reputation: 311023

readObject() returns null if and only if you wrote a null. The correct technique is to catch EOFException and when you get it close the stream and exit the reading loop.

Upvotes: 2

melihcelik
melihcelik

Reputation: 4599

If you want to read object into your program, then you have to use ObjectInputStream, not ObjectOutputStream.

And if you will store a bunch of objects, then use an appropriate Collection for writing to file and reading from it. The API documentation for readObject does not state that it will return null or throw an exception if EOF is reached. So to be on the safe side, use Collections.

You may also want to read API docs on ObjectInputStream and ObjectOutputStream.

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120566

Guava's Files.toByteArray does what you want so if fame in your code is a File, then

import com.google.common.io.Files;

...

byte[] fameBytes = Files.toByteArray(fame);

Upvotes: -1

Related Questions