Reputation: 195
i write ArrayLists into a file. I read it with FileInputStream. But always just the "first" ArrayList is appears by reading. I tried it with readInt() / wirteInt(), and loops, but there were always thrown exceptions, by calling readInt() --> EOF I want to read all ArrayList from this File into an ArrayList. My application needs to be persistent, so i serialized the ArrayLists.
write into file:
try {
FileOutputStream fos = new FileOutputStream(_cache, true);
ObjectOutputStream os = new ObjectOutputStream(fos);
// os.writeInt(newValueList.size()); // Save size first
os.writeObject(newValueList);
os.flush();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
read from file:
List cachedValueList = new ArrayList<String>();
ObjectInputStream o = new ObjectInputStream(new FileInputStream("caching.io"));
// int count = o.readInt(); // Get the number of regions
try {
cachedValueList.add(o.readObject());
} catch (EOFException e) {
o.close();
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Upvotes: 0
Views: 766
Reputation: 533560
If you are writing the same list many times, it will only write the list once. After that it will use the same reference but the contents will be the same (this is true of any object)
If you call reset()
between writeObject() it will send a fresh copy of the list each time.
Upvotes: 1