如何在Java11中关闭打开的程序后反序列化对象
我有一个程序,我试图在其中实现obejcts的保存和加载,但是我无法在程序关闭后让加载工作,因此有效地只有在程序打开时保存和加载工作,但一旦程序启动,就永远不会加载数据。我想这与过度劳累有关。我创建了一个测试程序,看看我是否可以使用一个简单的Person类使它工作。我将Peson对象存储在ArrayList中并序列化,然后反序列化。目前,我将所有加载的Person对象存储在JComboBox中。我在网上查过,找不到任何有用的东西。还请注意,我知道使用序列化并不是保存对象的最佳方法,但它适合用于我的程序
我的应用程序类:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
public class App extends JFrame {
public static JComboBox<Person> peopleBox;
public App(){
try {
Person.peopleList = loadList();
}
catch(IOException | ClassNotFoundException e){
System.out.println(e.getMessage());
}
try {
saveList(Person.peopleList);
}catch (IOException e){
System.out.println(e.getMessage());
}
peopleBox = new JComboBox<>();
peopleBox.setModel(getComboBoxModel(Person.peopleList));
add(peopleBox);
pack();
setSize(600, 400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public DefaultComboBoxModel<Person> getComboBoxModel(ArrayList<Person> peopleList){
Person[] comboBoxModel = peopleList.toArray(new Person[0]);
return new DefaultComboBoxModel<>(comboBoxModel);
}
public static void saveList(ArrayList<Person> peopleList) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.bin"));
objectOutputStream.writeObject(peopleList);
}
public static ArrayList<Person> loadList() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("test.bin"));
Person.peopleList = (ArrayList<Person>) objectInputStream.readObject();
return Person.peopleList;
}
public static void main(String[] args){
// Person p = new Person("Sean", 22);
try {
saveList(Person.peopleList);
}catch (IOException e){
System.out.println(e.getMessage());
}
App app = new App();
app.pack();
app.setVisible(true);
}
}
个人类别
import java.io.Serializable;
import java.util.ArrayList;
public class Person implements Serializable {
public int age;
public String name;
public static ArrayList<Person> peopleList = new ArrayList<>();
public Person(String name, int age){
this.age = age;
this.name = name;
peopleList.add(this);
for(Person p : peopleList){
System.out.println(p.toString());
}
}
public Person(){
}
public String toString(){
return "Name : " + name + " Age: " + age;
}
}
我希望当我将列表保存到“test.bin”文件时,关闭程序,然后再次打开它,它将加载列表并显示我在关闭程序之前创建的对象。谢谢你的帮助,谢谢
# 1 楼答案
在从文件加载Person之前,您正在保存一个空列表。 我建议采取这种做法: