File.mkdirs()创建目录而不是文件 [英] File.mkdirs() creating a directory instead of a file
问题描述
我正在尝试序列化以下类:
I am trying to serialize the following class:
public class Library extends ArrayList<Book> implements Serializable{
public Library(){
check();
}
使用该类的以下方法:
void save() throws IOException {
String path = System.getProperty("user.home");
File f = new File(path + "\\Documents\\CardCat\\library.ser");
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (f));
oos.writeObject(this);
oos.close();
}
但是,不是创建一个名为的文件库。 ser
,该程序正在创建一个名为 library.ser
的目录,其中没有任何内容。为什么是这样?
However, rather than creating a file called library.ser
, the program is creating a directory named library.ser
with nothing in it. Why is this?
如果它有用,save()方法最初是从这个方法(同一个类)中调用的:
If its helpful, the save() method is initially called from this method (of the same class):
void checkFile() {
String path = System.getProperty("user.home");
File f = new File(path + "\\Documents\\CardCat\\library.ser");
try {
if (f.exists()){
load(f);
}
else if (!f.exists()){
f.mkdirs();
save();
}
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
}
推荐答案
File.mkdirs()创建目录而不是文件
File.mkdirs() creating a directory instead of a file
这就是它应该做的事情。阅读Javadoc。没有关于创建文件的信息。
That's what it's supposed to do. Read the Javadoc. Nothing there about creating a file.
f.mkdirs();
f.mkdirs();
正是这条线创建了目录。它应该是
It is this line that creates the directory. It should be
f.getParentFile().mkdirs();
这篇关于File.mkdirs()创建目录而不是文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!