public void save() throws IOException {
File f = new File(path);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
FileOutputStream fout = new FileOutputStream(f, false);//overwrite, append set to false
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(this.vehicles);
out.close();
}
我有以下代码将vehicule类型的对象保存到文件中。但是,我不太清楚它是如何工作的,因为它是为我提供的样本,因为我是java领域的新手。
我想知道这些行的解释是什么if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
我想知道getParentFile().exists()
做了什么以及为什么我们在对文件本身感兴趣时搜索父文件。下一行的同样问题:为什么我们要在创建文件时对父目录感兴趣?
我想知道FileOutputStream
和ObjectOutputStream
之间的区别,以及为什么两个在以下行FileOutputStream fout = new FileOutputStream(f, false);//overwrite, append set to false
ObjectOutputStream out = new ObjectOutputStream(fout);
中彼此相邻使用
提前谢谢
答案 0 :(得分:2)
文件是指向文件系统上的文件或目录位置的指针。但是,如果要写入文件,则必须存在它所在的父目录。否则,您将获得IOException
。 mkdirs
调用将创建必要的父目录(或目录)以避免IOException
。
我不认为exists
检查确实是必要的,因为如果mkdirs
方法实际上没有创建任何内容,则返回false。
此外,您应该在finally
块内关闭OutputStream或使用Java 7 try-with-resources:
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f, false))) {
out.writeObject(vehicles);
}