文章字数:147,阅读全文大约需要1分钟
能够将对象写入到文件,并从文件中读取的操作(序列化,反序列化)
使用方法
需要被序列化的类必须实现Serializable
接口,最好声明字段private static final long serialVersionUID = 1L;
表示序列化对象的版本,防止多个序列化版本时冲突。
被序列化的类加上get
set
方法
序列化反序列化
1 2 3 4 5 6 7 8 9 10 11 12
| Student s1 = new Student("zhangsan"); Student s2 = new Student("lisi");
ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("test.txt")); os.writeObject(s1); os.writeObject(s2); os.close();
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("test.txt")); Student s1=(Student) ois.readObject(); Student s2=(Student) ois.readObject(); ois.close();
|
- 多个类读取比较麻烦,可以保持在集合里再序列化到文件中。