Reputation: 3
I am trying to write a populated tree to file using ObjectOutputStream
, but I am getting java.io.NotSerializableException
.
// build Huffman trie
HuffNode root = buildTrie(freq);
try{
FileOutputStream saveFile=new FileOutputStream("SaveObj.sav");
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(root);
save.close();
} catch(Exception exc){
exc.printStackTrace();
}
Here is my tree class
private class HuffNode implements Comparable<HuffNode> , Serializable {
private final char ch;
private final int freq;
private final HuffNode left, right;
HuffNode(char ch, int freq, HuffNode left, HuffNode right) {
this.ch = ch;
this.freq = freq;
this.left = left;
this.right = right;
}
// is the node a leaf node?
private boolean isLeaf() {
assert ((left == null) && (right == null)) || ((left != null) && (right != null));
return (left == null) && (right == null);
}
// compare, based on frequency
public int compareTo(HuffNode that) {
return this.freq - that.freq;
}}
Why the serialization not working?
Upvotes: 0
Views: 53
Reputation: 37645
HuffNode
is an inner class of some other class you haven't shown us.
An instance of an inner class holds on to an instance of the enclosing class. If the enclosing class is not Serializable
this will prevent an instance of the inner class from being serialized.
HuffNode
should probably be a static nested class.
private static class HuffNode implements Comparable<HuffNode> , Serializable
Upvotes: 1