Read more than one object from a file!

T

tranky

I've serializated more than one object inside a file with writeObject. It's
possible, now, to read that objects with the method readObject?!
I'm able to read the first object, not the others!

Can you help me?!?

thank u!
 
T

Thomas Hawtin

tranky said:
I've serializated more than one object inside a file with writeObject. It's
possible, now, to read that objects with the method readObject?!
I'm able to read the first object, not the others!

Can you help me?!?

I think first we'll need to know what is wrong. It should work fine.
Below is some code I wrote the other day (for production use it'd close
the streams within a finally, for instance).

Tom Hawtin

import java.io.*;
import java.util.*;

class Save {
public static void main(String[] args) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("checked.ser")
);
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("a", 1);
map.put("b", 2);
out.writeObject(
Collections.checkedMap(map, String.class, Integer.class)
);
List<Long> list = new ArrayList<Long>();
list.add(5L);
list.add(6L);
out.writeObject(Collections.checkedList(list, Long.class));
out.writeObject((Short)(short)42);
out.close();
}
}

import java.io.*;
import java.util.*;

class Load {
public static void main(String[] args) throws Exception {
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("checked.ser")
);
Map<String,Integer> map = (Map<String,Integer>)in.readObject();

System.out.println(map.getClass());
for (Map.Entry<String,Integer> entry : map.entrySet()) {
System.out.println(entry.getKey()+" - "+entry.getValue());
}

List<Long> list = (List<Long>)in.readObject();
System.out.println(list.getClass());
for (Long value : list) {
System.out.println(value);
}
System.out.println(in.readObject());
}
}
 
G

Gordon Beaton

I've serializated more than one object inside a file with
writeObject. It's possible, now, to read that objects with the
method readObject?! I'm able to read the first object, not the
others!

Did you write them all using the *same* ObjectOutputStream, and are
you attempting to read them using the *same* ObjectInputStream?

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top