I’ve got (an admittedly strange) try/catch block that checks if a File exists. If it doesn’t, then I create it and write a File to it. Then I read the File.
I have an ArrayList that is being initialized by reading an object from an ObjectInputStream. In the original writing of the file using a FileOutputStream and an ObjectOutputStream, if I call close() on them, then my ArrayList remains null. If I simply remove the calls to close(), everything goes as planned.
This seems backwards to me. I would think that the file system is somehow “locked” if I’ve got some type of stream open to it. That’s why I thought to close the outputStreams before using an inputStream. But no, Java won’t let this work unless I keep the outputStreams open.
Here’s my code, including the commented out calls to close() which allows this to work properly:
try {
File file = context.getFileStreamPath("file");
} catch (Throwable e) {
e.printStackTrace();
try {
FileOutputStream fileOutputStream = context.openFileOutput("file", Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
reminders = new ArrayList<Reminder>();
objectOutputStream.writeObject(reminders);
// fileOutputStream.close();
// objectOutputStream.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
try {
FileInputStream fileInputStream = context.openFileInput("file");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
if (objectInputStream != null) {
reminders = (ArrayList<Reminder>) objectInputStream.readObject();
}
} catch (Throwable t) {
t.printStackTrace();
}
You should not close the fileOutputStream. The close for objectOutputStream will close the fileOutputStream.
Closing the fileOutputStream beafore the objectOutputStream will prevent the objectObjectStream from flushing it’s contents to the file, since the fileOutputStream has already been closed.
Not sure why not closing either is allowing the code to work, unless the the objectOutputStream finalize method is flushing the contents when it goes out of scope.