标签:import his file turn obj stat fileinput system object
1.对象序列化的目的:持久化对象数据
2.对象序列化的条件:实现序列化的接口Serializable
import java.io.Serializable; public class MyObject implements Serializable{ /** * 实现序列化接口,才能持久化 */ //serialVersionUID用于标识该类,系统自动生成 private static final long serialVersionUID = -765378581853551685L; private String nameOfObj; public String getNameOfObj() { return nameOfObj; } public void setNameOfObj(String nameOfObj) { this.nameOfObj = nameOfObj; } }
public class TestIOObject { //写入一个对象 @Test public void test01() throws IOException { //创建一个对象 MyObject myObject=new MyObject(); myObject.setNameOfObj("我的对象"); //找到写入的目标文件 OutputStream os=new FileOutputStream(""); //创建对象流 ObjectOutputStream oos=new ObjectOutputStream(os); //将对象写入文件中 oos.writeObject(myObject); oos.flush(); oos.close(); } //读取一个对象 public void test02() throws IOException, ClassNotFoundException{ //找到要读取的文件 InputStream is=new FileInputStream(""); //创建对象流 ObjectInputStream ois=new ObjectInputStream(is); //读取一个对象 MyObject myObject=(MyObject)ois.readObject(); System.out.println(myObject.getNameOfObj()); } }
标签:import his file turn obj stat fileinput system object
原文地址:https://www.cnblogs.com/Unlimited-Rain/p/12569405.html