【发布时间】:2020-03-15 08:38:18
【问题描述】:
我使用下面的代码在一个文件中保存了近 10k 个对象:
boolean exists = Tools.getDeviceInfo().exists();
FileOutputStream fos = new FileOutputStream(Tools.getDeviceInfo(), true);
ObjectOutputStream oos = exists ?
new ObjectOutputStream(fos) {
protected void writeStreamHeader() throws IOException {
reset();
}
}:new ObjectOutputStream(fos);
oos.writeObject(deviceInfos);
现在,当我尝试读取文件时,它会抛出 OutOfMemory 异常。我该如何解决这个问题。下面是读取对象的代码。
FileInputStream fis = new FileInputStream(Tools.getDeviceInfo());
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<DeviceInfo> arrayList = new ArrayList<>();
try {
arrayList.addAll((ArrayList<DeviceInfo>)ois.readObject());
} catch (Exception e) {
e.printStackTrace();
}
ois.close();
return arrayList;
我想读取所有对象的原因是我想在 tableview 中显示所有数据,所以我需要将所有(10k 行)添加到 arraylist 并在 tableview 上显示。 有没有限制 readObject() 的选项,所以它只能从一个非常大的文件中检索几个对象。 我怎样才能改善这一点?请帮忙。
【问题讨论】:
标签: java arrays arraylist out-of-memory fileinputstream