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());
}
}