views:

54

answers:

2

I'm trying to read all the objects stored in a *.ser file and store them in a array of objects. How can I get the number of objects stored in that file(So that I can declare the array to be number_of_objects long)?

I've checked the API and was unable to find a Desirable function.

-edit-
A Part of the code:

Ser[] objTest2 = new Ser[number_of_objects];
for(int i=0; i<=number_of_objects, i++) {
    objTest2[i] = (Ser)testOS2.readObject();
    objTest2[i].printIt(); 
}
+3  A: 

What you want to look at is the ArrayList class.

It is basically a dynamically growing Array.

You can add items to it like so:

ArrayList list = new ArrayList();
list.add(someObject);
list.add(anotherBoject);

The list will grow as you add new items to it. So you don't have to know the size ahead of time.

If you need to get an array out if the List at the end you can use the toArray() method of List.

Object[] arr = list.toArray(new Object[list.size()]);

Edit:
Here is a general implementation of what you need:

List<Ser> objTest2 = new ArrayList<Ser>();
while (testOS2.available > 0) {
    Ser toAdd = ((Ser)testOS2.readObject());
    toAdd.printIt(); 
    objTest2.add(toAdd);
}

*I don't think available() is a reliable test for whether or not there are more bytes to read.

jjnguy
I don't think that I require that here. Here's a part of the code. -edited- code added in main post.
MoonStruckHorrors
@MoonStruckHorros You do require that (but do add generics). You need to deserialise the stream to find the number of (top-level) objects (unless you were to store that information somewhere ahead). / In general, arrays of references should be avoided - use `List` instead.
Tom Hawtin - tackline
A: 

Just keep reading objects until you get EOFException. That's what it's for.

EJP
Something wrong with this answer?
EJP