注意点:1、序列化并不保存静态变量
2、若父类未实现Serializable,子类实现了,父类需提供一个无参构造方法,且父类不会被序列化(无参构造方法只是用来构造父类)
3、Transient关键词可以用来阻止成员被序列化
4、只有成员变量能被序列化,成员函数不能被序列化
- TreeNode obj = new TreeNode(); //要实现Serializable接口
- obj.setId(1);
- //内存流
- //ByteArrayOutputStream os = new ByteArrayOutputStream();
- //ObjectOutputStream outStream = new ObjectOutputStream(os);
- //文件流
- FileOutputStream fos = new FileOutputStream("dat");
- ObjectOutputStream outStream = new ObjectOutputStream(fos);
- outStream.writeObject(obj);
- outStream.flush();
- outStream.close();
- //不知道为什么JAVA没有像C#里的同时支持输入输出Stream
- //ByteArrayInputStream in = new ByteArrayInputStream(os.toByteArray());
- //ObjectInputStream inStream = new ObjectInputStream(in);
- FileInputStream fin = new FileInputStream("dat");
- ObjectInputStream inStream = new ObjectInputStream(fin);
- TreeNode t = (TreeNode)inStream.readObject();
- System.out.println(t.getId());
- inStream.close();