需要被序列化的对象。
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Book implements Serializable {
int id;
String name;
String author;
}
序列化代码。
@Test
public void test9() throws IOException{
File file = new File("D:\\aaa.txt");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
ArrayList<Book> list = new ArrayList<>();
Book book1 = new Book(1, "张三的书", "zs");
Book book2 = new Book(2, "李四的书", "ls");
Book book3 = new Book(3, "王五的书", "ww");
list.add(book1);
list.add(book2);
list.add(book3);
oos.writeObject(list);
}
反序列化代码。
@Test
public void test10() throws IOException, ClassNotFoundException {
File file = new File("D:\\aaa.txt");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream oos = new ObjectInputStream(fis);
ArrayList<Book> list = (ArrayList<Book>) oos.readObject();
list.forEach(System.out::println);
}