对象序列化到本地文件 ObjectOutputstream ObjcetInputstream

时间:2021-09-25 03:32:28
package com.main.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; public class ObjectOutputStreamDemo { public static void main(String[] args) throws ClassNotFoundException {
// TODO Auto-generated method stub
// ObjectOutPutStreamDemo();
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c:\\OOS.txt"));
Object readObject = ois.readObject();
Person person = (Person)readObject;
System.out.println(person.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } private static void ObjectOutPutStreamDemo() {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:\\OOS.txt"));
Person person = new Person("zhangsan",12);
oos.writeObject(person);
System.out.println(person.toString()); oos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }