我正在尝试序列化以下类:
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();
}
但是,该程序并没有创建名为 library.ser
的文件,而是创建了一个名为 library.ser
的目录,其中没有任何内容。为什么是这样?
如果有帮助,save() 方法最初是从此方法(属于同一类)调用的:
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() creating a directory instead of a file
这就是它应该做的。阅读 Javadoc。没有关于创建文件的内容。
f.mkdirs();
正是这一行创建了目录。应该是
f.getParentFile().mkdirs();
关于java - File.mkdirs() 创建目录而不是文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15212845/