gpt4 book ai didi

java - 将对象从文件读取到输入流

转载 作者:行者123 更新时间:2023-12-02 05:41:28 29 4
gpt4 key购买 nike

我目前正在开发一个简单的ObjectInputStreamObjectOutputStream,我已经阅读了documentation和 Java tutorial并熟悉基础知识;但是,在尝试编译我的程序时,我遇到了一个错误,该错误可能与我对 Map 和对象输入/输出的组合的误解有关,特别是输入部分。

我有一个 .dat 文件,我试图从中读取映射到 TreeMap 的对象列表:

public class Product implements Serializable 
{
private static final long serialVersionUID = 1L;
private int code;
private String name;
private int quatity;

// Setters and Getters

}

上面是Product对象的代码片段,它本身实现了Serialized。我包含了该片段,以防问题出在此处。

对于此问题,假设 .dat 不为空并且包含格式正确的数据。

这是我的ObjectInputStream代码:

try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file))) {
while (true) {
try {
products = (Map<Integer, Product>) inputStream.readObject();
}
catch (ClassNotFoundException cnfException {
System.out.println("ClassNotFoundException: " + cnfException.getMessage());
}
catch (EOFException eofException) {
System.err.println("EOFException: " + eofException.getMessage());
}
}

尝试运行此代码时,出现以下错误(强制转换错误):

Screenshot of Error Message

以下是我将 Product 对象写入 .dat 文件的方法:

try (ObjectOutputStream outputStream = new ObjectOutputStream(new    FileOutputStream(fileName))) {
for (int i = 0; i < products.size(); i++) {
outputStream.writeObject(products.get(i));
}
}

隔离错误后,我知道当我点击 products = 部分时会发生错误。我不确定这是一个复合问题还是两个问题之一:

  1. 我没有正确从文件中获取数据来填充 TreeMap
  2. 我误解了 ObjectInputStream 的实现

最佳答案

听起来你最初只是写了 Product反对ObjectOutputStream ,而不是 Map<Integer, Product> 。如果是这种情况,您需要类似的东西:

Map<Integer, Product> products = new TreeMap<>();
try (ObjectInputStream input = new ObjectInputStream(new FileInputStream(file))) {
while (true) {
Product product = (Product) input.readObject();
products.put(product.getCode(), product); // Or whatever
}
} catch (EOFException e) {
// Just finish? Kinda nasty...
}

当然,当它到达流末尾时会抛出异常 - 您可能需要考虑如何干净地检测到该异常,而不仅仅是处理异常。

关于java - 将对象从文件读取到输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24479069/

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