我有(无可否认奇怪)try/catch块检查是否存在File
。如果没有,那么我创建它并写一个File
它。然后我读了File
。Java不希望我在使用inputStream之前关闭outputStream?
我有一个ArrayList
正在通过从ObjectInputStream
读取对象进行初始化。在原始文件中使用FileOutputStream
和ObjectOutputStream
,如果我对其调用close()
,那么我的ArrayList
仍然为null
。如果我只是删除电话close()
,一切都按计划进行。
这似乎倒退给我。如果我有某种类型的stream
对它开放,我会认为文件系统以某种方式被“锁定”。这就是为什么我想在使用inputStream
之前关闭outputStreams
。但是,不,Java不会让这个工作,除非我保持打开outputStreams
。
这里是我的代码,包括注释掉调用close()
,让这个正常工作:
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();
}
你是否得到任何异常堆栈跟踪? –
'if(objectInputStream!= null)'check在这里应该是多余的(构造函数调用永远不会返回'null')。 –
看起来你正在写一个空的ArrayList到流中。如果你写一条记录然后关闭它会发生什么?它让我怀疑输出流对象是否为你的对象分配了一些最小空间,除非你关闭它,否则它还没有被GC'd处理过。 – ethrbunny