package object;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ToStream {
public static void toStream(Person person) throws IOException{
FileOutputStream fout = new FileOutputStream("D:\\obj.txt");
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(person);
}
public static Person toObject() throws IOException, ClassNotFoundException{
FileInputStream in = new FileInputStream("D:\\obj.txt");
ObjectInputStream input = new ObjectInputStream(in);
return (Person)input.readObject();
}
public static void main(String[] args) {
//对象序列化
Person person = new Person();
person.setAge(23);
person.setName("张三");
try {
ToStream.toStream(person);
try {
Person ps = (Person)toObject();
System.out.println(ps.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
转载于:https://my.oschina.net/zhanghongbin01/blog/547727