首先先创造一个Student对象类同时实现序列化接口
import java.io.Serializable; public class Student implements Serializable{ /** * */ private static final long serialVersionUID = 1L; String name; int age; String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Student(String name, int age, String sex) { super(); this.name = name; this.age = age; this.sex = sex; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", sex=" + sex + "]"; } }
然后写一个测试类
public class SerializableTest { public static void main(String[] args) { // TODO Auto-generated method stub //method1(); method2(); } private static void method2() { // TODO 读文件并反序列化成对象 try { ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:\\1.txt")); Object o = in.readObject(); System.out.println(o.toString()); in.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void method1() { // TODO 对象序列化并输出到文件 try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\\1.txt")); Student stu = new Student("杨磊",11,"男"); out.writeObject(stu); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
method1输出到文件,method2从文件读取并反序列化成对象
从文件读取的结果
Student [name=杨磊, age=11, sex=男]
原文:https://www.cnblogs.com/cnbk/p/13025233.html