Reputation: 279
I have a List of list of some objects defined in a data structure: List > someObject1=new ArrayList();
And I have written few someObject items to a fileXY using function writeData :
void writeData(List <List<Integer>> someObject1, File XY) throws IOException {
try(ObjectOutputStream outFile = new ObjectOutputStream(new FileOutputStream(XY,true)))
outFile.writeObject(someObject1);
}
catch( IOException ex) { ex.printStackTrace(); }
}
Now I tried to read it using function readData:
void readData(File XY) throws IOException {
try (ObjectInputStream inFile=new ObjectInputStream(new FileInputStream(XY))) {
List <List <MyClass>> someObject2=(List <List <MyClass>>)inFile.readObject();
}
catch( IOException ex) { ex.printStackTrace(); }
}
But it is giving me error :
java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1363)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
Can anyone help me with it. Is there something wrong with the casting while reading this data structure?
Had it been just a list of objects, I could have read it by casting the readObject() with
(List<MyClass>).
Why the same thing doesn't work for the list-of-list of objects?
This is outline of MyClass:
public class MyClass implements Serializable {
private long aa;
private List <Integer> bb;
public MyClass(long a,List <Integer> b) {
aa=a;
bb=b;
}
public long getA() {
return aa;
}
public List<Integer> getB () {
return bb;
}
}
Upvotes: 1
Views: 4884
Reputation: 37710
This definitely works for me:
public static final String FILE = "file.b";
public static class MyClass implements Serializable {
private long aa;
private List<Integer> bb;
public MyClass(long a, List<Integer> b) {
aa = a;
bb = b;
}
}
public static void main(String[] args) throws FileNotFoundException, IOException,
ClassNotFoundException {
List<List<MyClass>> list = new ArrayList<>();
list.add(new ArrayList<>());
list.get(0).add(new MyClass(5, new ArrayList<>()));
ObjectOutputStream outFile = new ObjectOutputStream(new FileOutputStream(new File(FILE)));
outFile.writeObject(list);
outFile.close();
ObjectInputStream inFile = new ObjectInputStream(new FileInputStream(new File(FILE)));
List<List<MyClass>> list2 = (List<List<MyClass>>) inFile.readObject();
System.out.println(list2);
}
Note: this works even if I don't add any MyClass
to list.get(0)
, and even if I don't add a list to list
.
Several possible causes for your problem come to my mind:
UPDATE:
Maybe you use a non serializable attribute in your serializable class MyClass
. If so, you should override writeObject()
and readObject()
to serialize/deserialize such an attribute of your class properly.
Take a look at this: http://marxsoftware.blogspot.fr/2014/02/serializing-java-objects-with-non.html
Upvotes: 1