0

我目前正在研究一个简单的ObjectInputStreamand ObjectOutputStream,我已经阅读了文档和 Java教程,并且熟悉基础知识;但是,在尝试编译我的程序时,我遇到了一个错误,这可能与我对s 和 Object input/output组合的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对象的代码片段,它本身实现了Serializable. 如果问题出在那儿,我会包括片段。

对于这个问题,假设 .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());
        }   
}

尝试运行此代码时,我收到以下错误(Cast 错误):

错误信息截图

这是我将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
4

1 回答 1

2

听起来您最初只是将Product对象写入 a ObjectOutputStream,而不是 a 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...
}

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

于 2014-06-29T18:46:52.270 回答