我有一个程序,我试图在其中实现对象的保存和加载,但是在程序关闭后我无法让加载工作,因此只有在程序打开时有效地保存和加载工作,但没有数据永远程序启动后加载。我认为这与过度阅读有关。我创建了一个测试程序,看看我是否可以只使用一个简单的 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;
}
我希望当我将列表保存到“test.bin”文件时,关闭程序,然后再次打开它,它将加载列表并显示我在关闭程序之前创建的对象。我感谢任何帮助,谢谢。
猛跑小猪
相关分类