Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count number of objects stored in a *.ser file

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(); 
}
like image 724
DM_Morpheus Avatar asked Jul 13 '10 13:07

DM_Morpheus


1 Answers

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.

like image 165
jjnguy Avatar answered Nov 14 '22 23:11

jjnguy