[英]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.