如何在java中序列化和反序列化kdtree

时间:2013-01-05 18:18:47

标签: java serialization deserialization kdtree

我有一个kdtree,其节点由以下字段组成: public static class Node实现Serializable     {

    public int discriminator;
    public double value; 

    public Node leftChild;
    public Node rightChild;
    public DataPoint object;
    }

其中DataPoint定义:

公共静态类DataPoint实现Serializable      {          public Comparable X;          公众可比Y;          public Comparable Z;

     public double latitude;
     public double longitude;

     public ArrayList<String> text = new ArrayList<String>(); 
     }

我想序列化树,存储在文件中并在回答范围查询时反序列化。我对这个概念序列化的理解并不好。从我收集的任何内容中,我都写了以下函数,这些函数不起作用。有人可以帮忙吗?

 public static void serialize(final OutputStream out, kdtrees.Node node) throws IOException
 {
        if( node == null ) 
        {
            //out.write( "()".getBytes() );
            //write to an output leaf file
            out.write("#".getBytes());

        } 
        else 
        {
            //out.write( "(".getBytes() );
            ((ObjectOutputStream) out).writeObject(node);
            serialize( out, node.leftChild );
            serialize( out, node.rightChild );
            //out.write( ")".getBytes( ) );
        }
    }


 public static kdtrees.Node deserialize(final ObjectInputStream reader) throws IOException, ClassNotFoundException 
 {

                  StringTokenizer st = new StringTokenizer(reader.readObject().toString()); 
                  String curToken = st.nextToken().toString();
                  while(st.hasMoreTokens())
                  { 
                      if(curToken.equals("#".trim()))
                          return null;


                      kdtrees.Node e = (kdtrees.Node)reader.readObject();

                       e.leftChild = deserialize(reader);
                       e.rightChild = deserialize(reader);

                    return e;

                  }
               return null;   


    } 

1 个答案:

答案 0 :(得分:1)

将任意OutputStream投射到ObjectOutputStream只会失败。相反,使用new ObjectOutputStream(outputStream)围绕OutputStream创建包装,并为InputStream创建相同的内容。