我試圖序列化一個對象具有以下到文件:的ObjectOutputStream沒有寫入文件
// fill with some test data
ArrayList<Transaction> transactions = new ArrayList<>();
transactions.add(new Transaction("Internet", "2016-09-20", -28));
transactions.add(new Transaction("Groceries", "2016-09-20", -26));
//serialize transactions
try {
// File f = new File("transactions.ser");
// OutputStream file = new FileOutputStream(f);
// OutputStream buffer = new BufferedOutputStream(file);
// ObjectOutput output = new ObjectOutputStream(buffer);
File f = new File("transactions.ser");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(transactions);
out.flush();
out.close();
FileInputStream fis = new FileInputStream(f);
ObjectInputStream in = new ObjectInputStream(fis);
Object o = in.readObject();
System.out.println(o);
}
catch(IOException e){
System.out.println("IOException");
}
catch(ClassNotFoundException e) {
System.out.println("ClassNotFoundException");
}
..however IOException異常被拋出。被註釋掉的代碼確實可以創建文件,但它是空的,所以我認爲這不是權限問題?經過一些閱讀後,我發現ObjectOutputStream,但不會寫入文件。我究竟做錯了什麼?
那麼你正在吞嚥異常,只是打印'IOException'。打印出異常本身,它會告訴你什麼是錯的。請注意,您還應該使用try-with-resources來處理關閉...... –
而不是'System.out.println(「IOException」)''使用'e.printStackTrace()'。請[編輯]問題並添加正確格式化的結果堆棧跟蹤。堆棧跟蹤是在發生異常時首先要查看的地方 - 不要用無意義的打印壓縮它。 – RealSkeptic