需要被序列化的对象。
@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);
}
本文展示了如何使用Java进行对象序列化和反序列化操作,通过`ObjectOutputStream`将ArrayList包含Book对象的数据写入文件,再利用`ObjectInputStream`从文件中读取并打印出序列化的数据。
1175

被折叠的 条评论
为什么被折叠?



