gpt4 book ai didi

java - OnSave 方法与 onload 方法一起使用吗?

转载 作者:行者123 更新时间:2023-12-01 04:43:04 26 4
gpt4 key购买 nike

我已经创建了一个 onLoad 方法来在程序中使用序列化,但我想同时使用 onSave 方法,这样当程序关闭并再次启动时,我就不必一次又一次地填充我的 Jlists。

我尝试创建自己的 onSave 函数,但无法使其正常工作。

有人可以给我举个例子或者给我 onSave 函数来让我的序列化高效工作吗?

这是我的 onLoad() 方法:

private void onLoad()
{//Function for loading patients and procedures
File filename = new File("ExpenditureList.ser");
FileInputStream fis = null;
ObjectInputStream in = null;
if(filename.exists())
{
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
Expenditure.expenditureList = (ArrayList<Expenditure>) in.readObject();//Reads in the income list from the file
in.close();
} catch (Exception ex) {
System.out.println("Exception during deserialization: " +
ex);
ex.printStackTrace();
}
}

这是我对 onSave 方法的尝试:

try
{
FileInputStream fileIn =
new FileInputStream("Expenditure.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
expenditureList = (ArrayList<Expenditure>) in.readObject();


for(Expenditurex:expenditureList){
expenditureListModel.addElement(x);
}


in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c1)
{
System.out.println("Not found");
c1.printStackTrace();
return;
}

最佳答案

您可以只写入 ObjectOutputStream:

public void onSave(List<Expenditure> expenditureList) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File("ExpenditureList.ser")));
out.writeObject(expenditureList);
out.flush();
}
catch (IOException e) {
// handle exception
}
finally {
if (out != null) {
try {
out.close();
}
catch (IOException e) {
// handle exception
}
}
}
}

public List<Expenditure> onLoad() {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(new File("ExpenditureList.ser")));
return (List<Expenditure>) in.readObject();
}
catch (IOException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
// handle exception
}
}
}
return null;
}

关于java - OnSave 方法与 onload 方法一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16232642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com