我想讀取和寫入一個文件的對象。這是我的嘗試:在文件中寫入和讀取對象
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class SaveOpen implements Serializable
{
private static String fileName;
private ArrayList<Person> list = new ArrayList<Person>();
public SaveOpen() {
fileName = "file.txt";
}
//Reader
public static Object deserialize() throws IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream(fileName);
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
Object obj = ois.readObject();
ois.close();
return obj;
}
//Writer
public static void serialize(Object obj)
throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.close();
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public ArrayList<Person> getListPersons() {
return list;
}
}
但是,我不知道這是否是正確的方法,也不知道如何在類中實現這一點。該對象是Person
,我想保存並從文件中讀取該對象。它是否應該完成到.txt
文件?任何人可以清理的東西?謝謝!
如果你使用流序列化一個對象,那麼你正在編寫二進制數據,而不是文本,所以你不應該寫入'.txt'文件。 – khelwood
沒有什麼能夠阻止你將它寫入'.txt'文件,但是這表明內容是文本,而不是。 – Kayaman
https://docs.oracle.com/javase/8/docs/technotes/guides/serialization/ <=有一些可用的例子。 – Fildor