gpt4 book ai didi

java - 从文件读取对象的 ArrayList 时出错?

转载 作者:行者123 更新时间:2023-12-02 11:40:38 24 4
gpt4 key购买 nike

我有一个对象数组存储在“rootFile”中。我想将对象读回到另一个 ArrayList 中。到目前为止我尝试过这个:

List<NoteCard> cardArray = new ArrayList<>();

try {
FileInputStream fis = openFileInput(rootFile);
ObjectInputStream ois = new ObjectInputStream(fis);
cardArray = (List<NoteCard>)ois.readObject();
ois.close();
fis.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}

最佳答案

您可以通过执行以下操作删除未经检查的强制转换:

ArrayList<NoteCard> cardArray = new ArrayList<>();

try {
FileInputStream fis = openFileInput(rootFile);
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
if (object instanceof ArrayList) {
ArrayList arrayList = (ArrayList) object;
for (Object object : arrayList) {
cardArray.add((NoteCard) object);
}
}
ois.close();
fis.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}

关于java - 从文件读取对象的 ArrayList 时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48593569/

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