Java 将对象从文件读取到输入流
我目前正在编写一个简单的Java 将对象从文件读取到输入流,java,objectinputstream,treemaps,Java,Objectinputstream,Treemaps,我目前正在编写一个简单的ObjectInputStream和ObjectOutputStream,我已经阅读了和Java,并且熟悉基础知识;然而,在试图编译我的程序时,我遇到了一个错误,这可能与我对Maps和对象输入/输出的组合,特别是输入部分的误解有关 我有一个.dat文件,我正试图从中读取映射到树映射的对象列表: public class Product implements Serializable { private static final long serialVersio
ObjectInputStream
和ObjectOutputStream
,我已经阅读了和Java,并且熟悉基础知识;然而,在试图编译我的程序时,我遇到了一个错误,这可能与我对Map
s和对象输入/输出的组合,特别是输入部分的误解有关
我有一个.dat文件,我正试图从中读取映射到树映射的对象列表:
public class Product implements Serializable
{
private static final long serialVersionUID = 1L;
private int code;
private String name;
private int quatity;
// Setters and Getters
}
上面是产品
对象本身的代码片段-实现可序列化
。如果问题出在那里,我会把碎片放进去
对于这个问题,假设.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());
}
}
隔离了错误后,我知道当我点击products=
部分时会发生错误。我不确定这是一个复合问题还是两个问题之一:
我没有正确地从文件中获取数据以填充TreeMap
我误解了ObjectInputStream
听起来好像您最初只是将产品
对象写入对象输出流
,而不是映射
。如果是这样的话,您需要:
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...
}
Map products=newtreemap();
try(ObjectInputStream输入=新ObjectInputStream(新文件inputstream(文件))){
while(true){
Product=(Product)input.readObject();
products.put(product.getCode(),product);//或其他任何内容
}
}捕获(EOFEException e){
//刚刚结束?有点恶心。。。
}
当然,当它到达流的末尾时,会抛出一个异常-您可能需要考虑如何干净地检测它,而不仅仅是处理异常。如何创建.dat文件?似乎写的是产品对象,而不是地图。让我在问题中添加一个描述。
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...
}