我基本上做一個日記應用程序,其中每個單獨的日記條目需要堅持,我想保留所有條目在一個單一的文件。序列化多個條目到同一個文件
我見過噸教程上序列化一個對象,所以我想出了這個解決方案,(不工作)但即使我設法解決它,感覺就像一個草率的解決方案。
(在這裏,我試圖序列一個ArrayList,每一次我保存的條目時,我反序列化列表,再次序列化之前添加新條目列表)
爲了澄清,我的問題是:這是將對象保存到同一個文件的好方法嗎?
還是沒有人有一些關於別的東西的提示我應該嘗試一下,關於這個視頻或文檔的鏈接也很感激。
public class Serializer
{
//Calls readFile and adds the returned entries to an ArrayList
//Add the target object to the list and write to the file
public static void writeToFile(Object target)
{
ArrayList entries = new ArrayList();
entries = readFile();
entries.add(target);
String filename = "entries.bin";
FileOutputStream fileOut = null;
ObjectOutputStream objOut = null;
try
{
fileOut = new FileOutputStream(filename);
objOut = new ObjectOutputStream(fileOut);
objOut.writeObject(entries);
objOut.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
//Reads the file and returns all entries in a list
public static ArrayList readFile()
{
ArrayList persistedEntries = new ArrayList<>();
String filename = "entries.bin";
FileInputStream fileIn = null;
ObjectInputStream objIn= null;
try
{
fileIn = new FileInputStream(filename);
objIn = new ObjectInputStream(fileIn);
persistedEntries = (ArrayList) objIn.readObject();
objIn.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return persistedEntries;
}
}
這可能幫助,如果你還別說在這種方式,它「不工作」 - 它拋出一個異常?哪一個? – Hulk
我實際上並不確定什麼是不工作的,因爲我得到一個索引超出範圍的異常,如果我已經理解不應該能夠發生的ArrayLists。但我只試圖運行程序,而不是自己的方法。 但是,正如你所看到的,我的問題並不是關於代碼不工作的事實,我只是想看看這個「想法」是否好,或者如果我完全錯過了某些東西,方向。 :) –
看着你的代碼,我注意到你在編寫一個文件之前總是「讀取」。必須檢查空白文件'entries.bin'以查看返回的ArrayList對象是什麼? – jrbeverly