我目前正在研究一个简单的ObjectInputStream
and 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 =
部分时会发生错误。我不确定这是一个复合问题还是两个问题之一:
- 我没有正确地从文件中获取数据以填充
TreeMap
- 我误解了
ObjectInputStream