Jürgen K.
Jürgen K.

Reputation: 3487

Saving HashMap with FileOutputStream

I'm trying to write a HashMap with the FileOutputStream. This is what my code looks like.

    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();
            } 

        }
}

The Problem is that the "write" function is not applicable for the argument. What can i do?Thanks

Upvotes: 0

Views: 590

Answers (3)

rzo1
rzo1

Reputation: 5751

In addition to the previous answers, it has to be additionaly mention, that the Mat class originates from OpenCV. According to its Javadoc, it does not implement the Serializable interface. Thus, it will not be properly serializable via object serialization in Java.

Basically you can use a third-party object serialization library, which supports serialization without implementing Serializable. Related: Serializing a class, which does not implement Serializable

An other way to persist your data would be to implement your own custom file format in CSV or XML. For example:

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

This can be easily parsed / written using Apache Commons IO classes or JDK basic file io.

Upvotes: 3

Jan
Jan

Reputation: 13858

If you use ObjectOutputStream to serialize your data, it's important that you call the correct write*() method depending on the type of data you want to store. See the JavaDoc for ObjectOutputStream.writeObject()

        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();
        } 

Upvotes: 1

Maxim Sharai
Maxim Sharai

Reputation: 614

Use the writeObject() method instead of the write() method:

out.writeObject(obj);

Upvotes: 1

Related Questions