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;
}
}
outFile?ObjectOutputStreamandObjectInputStreamafter you write/read to it!trywill implicitely close it only if it's atry-with-resourcelike this:try(stream declaration) { code }