我正在尝试序列化以下类:
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);
}
}
f.createNewFile()
,来创建不存在的文件。 - ddmpsnew FileOutputStream()
会自动完成这个任务。 - user207421FileNotFoundException
让我感到困惑。 - ddmpsFileOutputStream
时,如果出现目录未找到的情况,这就是为什么要使用mkdirs()
的原因。 - user207421