【Java】序列化&反序列化
Student.java
package LearnJava15;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
}
package LearnJava15;
import java.io.*;
public class ObjectStreamDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
write();
read();
}
//反序列化
private static void read() throws IOException, ClassNotFoundException {
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:\\MyProject\\Java\\Demo2\\src\\LearnJava15\\oss.txt"));
Object obj=ois.readObject();
Student s=(Student) obj;
System.out.println(s.getName()+","+s.getAge());
ois.close();
}
//序列化
private static void write() throws IOException {
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:\\MyProject\\Java\\Demo2\\src\\LearnJava15\\oss.txt"));
Student s=new Student("小A",22);
oos.writeObject(s);
oos.close();
}
}
本文来自博客园,作者:木子欢儿,转载请注明原文链接:https://www.cnblogs.com/HGNET/p/16198285.html