[英]Write and read object to and from file
我想讀取和寫入文件的對象。 這是我的嘗試:
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
文件進行嗎? 誰可以澄清事情? 謝謝!
如果你想讓文件是人類可讀的,我建議把它保存為xml。
示例:
對象類
import java.io.Serializable; public class Person implements Serializable { private String username; private int id; public String UserName() { return username; } public void setUserName(String str) { username = str;} public int ID() { return id; } public void setID(int ID) { id = ID; } }
-Serializer /解串器
import Settings.Person;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class XmlSerializer
{
//File path to serialize to and deserialize from
private static final String SERIALIZED_FILE_NAME = "yourSavePath.xml";
//Insert person object and save as xml file to chosen filepath
public static void Serialize(Person person)
{
try
{
FileOutputStream os = new FileOutputStream(SERIALIZED_FILE_NAME);
XMLEncoder encoder = new XMLEncoder(os);
encoder.writeObject(person);
encoder.close();
}
catch(FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
//Deserialize xml file into person object
public static Person Deserialize()
{
try
{
FileInputStream os = new FileInputStream(SERIALIZED_FILE_NAME);
XMLDecoder decoder = new XMLDecoder(os);
Person p = (Person)decoder.readObject();
decoder.close();
return p;
}
catch(FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
return null;
}
}
你已經做對了。 您可以在txt文件中安全對象,盡管它沒有多大意義,我寧願使用二進制文件。
要將多個對象存儲在單個文件中,只需將它們打包到Collection中,然后序列化Collection對象即可。
從文件中讀取對象時,通過instanceof檢查其類並將其轉換為任何類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.