文
章
目
录
章
目
录
学习如何在Java中序列化和/或反序列化ArrayList,附带易于理解的示例。请注意,列表中的元素也必须是可序列化的。
1.序列化
在Java中,ArrayList类默认是可序列化的。这实际上意味着我们不需要显式实现Serializable接口来序列化ArrayList。我们可以直接使用ObjectOutputStream来序列化ArrayList,使用ObjectInputStream来反序列化ArrayList对象。
存储在ArrayList中的元素也应该是可序列化的,否则程序将抛出NotSerializableException异常。
1.1. 序列化字符串ArrayList
以下是一个示例Java程序,用于持久化一个字符串ArrayList。
ArrayList<String> namesList = new ArrayList<>(List.of("alex", "brian", "charles"));
try (FileOutputStream fos = new FileOutputStream("listData");
ObjectOutputStream oos = new ObjectOutputStream(fos);) {
oos.writeObject(namesList);
} catch (FileNotFoundException e) {
log.error("File not found : ", e);
throw new RuntimeException(e);
} catch (IOException e) {
log.error("Error while writing data : ", e);
throw new RuntimeException(e);
}
程序输出:该列表被序列化在项目根目录下。在FileOutputStream构造函数中提供文件路径。
1.2. 序列化对象ArrayList
以下是一个Java程序,用于序列化一个Employee对象ArrayList。Employee类实现了Serializable接口。
@Data
@AllArgsConstructor
@NoArgsConstructor
class Employee implements Serializable {
private Long id;
private String firstName;
private String lastName;
}
ArrayList<Employee> employees = new ArrayList<>();
employees.add(new Employee(1L, "lokesh", "gupta"));
employees.add(new Employee(2L, "brian", "motto"));
try (FileOutputStream fos = new FileOutputStream("employeeData");
ObjectOutputStream oos = new ObjectOutputStream(fos);) {
oos.writeObject(employees);
} catch (FileNotFoundException e) {
log.error("File not found : ", e);
throw new RuntimeException(e);
} catch (IOException ioe) {
log.error("Error while writing data : ", ioe);
ioe.printStackTrace();
}
请注意,如果Employee类没有实现Serializable接口,将会收到此错误。
java.io.NotSerializableException: com.howtodoinjava.demo.model.Employee
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
2. 反序列化
2.1. 反序列化字符串列表
Java程序用于反序列化字符串列表并验证列表内容。我们正在反序列化在前面示例中序列化的相同列表。
ArrayList<String> list = null;
try (FileInputStream fis = new FileInputStream("listData");
ObjectInputStream ois = new ObjectInputStream(fis);) {
list = (ArrayList) ois.readObject();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
}
//Verify list data
for (String name : list) {
System.out.println(name);
}
程序输出:
alex
brian
charles
2.2. 反序列化对象列表
Java程序用于反序列化对象列表并验证列表内容。我们正在反序列化在前面示例中序列化的相同员工列表。
ArrayList<Employee> employeesList = null;
try (FileInputStream fis = new FileInputStream("employeeData");
ObjectInputStream ois = new ObjectInputStream(fis);) {
employeesList = (ArrayList) ois.readObject();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
}
//Verify list data
for (Employee employee : employeesList) {
System.out.println(employee);
}
程序输出:
Employee [id=1, firstName=lokesh, lastName=gupta]
Employee [id=2, firstName=brian, lastName=motto]
以上就是Java中序列化和反序列化ArrayList的全部内容。