序列化与反序列化

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 test1 {

public static void main(String[] args) throws Exception {

// TODO Auto-generated method stub

method2();

}

// 反序列化ObjectInputStream

public static void method2() throws Exception  {

FileInputStream fis=new FileInputStream("D:\\iotest\\person.txt");

ObjectInputStream ois=new ObjectInputStream(fis);

Object o=ois.readObject();

Person p=(Person)o;

System.out.println(p);

ois.close();

fis.close();

System.out.println("反序列化成功");

}

// 将对象 序列化 到磁盘中

// ObjectOutputStream 高级流  需要初级流

public static void method1() throws IOException {

FileOutputStream fos=new FileOutputStream("D:\\iotest\\person.txt");

ObjectOutputStream oos=new ObjectOutputStream(fos);

Person p1=new Person("tom",18);

oos.writeObject(p1);

oos.flush();

oos.close();

fos.close();

System.out.println("序列化完成");

}

}

你可能感兴趣的:(序列化与反序列化)