Java学习笔记【十一、序列化】

序列化的条件

  • 实现Serializable接口
  • 所有属性必须是可序列化的,或标记为transient(不做序列化)

序列化-将对象输出为序列化文件

ObjectOutputStream

反序列化-将序列化结果读取为对象

ObjectInputStream

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

    public static void main(String[] args) {
	// TODO Auto-generated method stub
	People p = new People();
	p.name = "Tom";
	p.age = 18;
	p.sex = "female";
	p.num = 12321;

	String path = "E:/JavaFile/tempFile/p.ser";

	try {
		FileOutputStream fileOut = new FileOutputStream(path);
		ObjectOutputStream out = new ObjectOutputStream(fileOut);
		out.writeObject(p);
		out.close();
		fileOut.close();
		System.out.println("Write complete");

		People p2 = new People();
		FileInputStream fileIn = new FileInputStream(path);
		ObjectInputStream in = new ObjectInputStream(fileIn);
		p2 = (People) in.readObject();
		p2.Print();
		in.close();
		fileIn.close();
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

    }

    }

class People implements java.io.Serializable {
String name;
int age;
String sex;
transient int num;// 序列化后该属性未在序列化结果中,所以反序列化后该属性无值

void Print() {
	System.out.println("name:" + name + ",age:" + age + ",sex:" + sex + ",num:" + num);
}
}
posted @ 2017-03-02 23:49  l.shane  阅读(189)  评论(0编辑  收藏  举报