我正在尝试用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,它没有实现Serializable
接口。因此,它将无法通过Java中的对象序列化进行正确的序列化。
基本上,您可以使用第三方对象序列化库,该库支持序列化,而无需实现Serializable
。相关:序列化一个类,该类不实现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.
使用writeObject()方法而不是write()方法:
out.writeObject(obj);
如果使用ObjectOutputStream
序列化数据,则根据要存储的数据类型调用正确的write*()
方法非常重要。参见ObjectOutputStream.writeObject()
的JavaDoc
try {
FileOutputStream fileOut = new FileOutputStream("C:\Users\Juergen\fileoutputstream.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOutput);
out.writeObject(obj); //Writes an Object!
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}