我正在尝试使用 FileOutputStream 编写 HashMap。 这就是我的代码的样子。
public class ObjectStream implements Serializable{
public void serialize(HashMap<String, Mat> obj){
try {
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\Juergen\\fileoutputstream.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOutput);
out.write(obj);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
问题是“write”函数不适用于该参数。我能做什么?谢谢
最佳答案
除了前面的答案之外,还必须额外提及的是,Mat
类源自 OpenCV。根据其 Javadoc,它没有实现 Serialized
接口(interface)。因此,它无法通过 Java 中的对象序列化正确序列化。
基本上,您可以使用第三方对象序列化库,该库支持序列化,而无需实现 Serialized
。相关:Serializing a class, which does not implement Serializable
保存数据的另一种方法是在 CSV
或 XML
中实现您自己的自定义文件格式。例如:
key1
0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
key2
0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
这可以使用 Apache Commons IO 类或 JDK 基本文件 io 轻松解析/编写。
关于java - 使用 FileOutputStream 保存 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34268652/