2008-12-12 39 views
1

我還有一個問題,系列化,但這次串行二進制時,它是關於Java的本機序列導入。我必須序列化在另一個java文件中生成的隨機樹。我知道序列化和反序列化是如何工作的,但是當我使用java.io.Serializable使用二進制序列化時,我遵循的例子並不像我使用它時那樣工作,比如說一個簡單的對象。這裏是我的代碼段:實現樹時使用java.io.Serializable?

import java.io.*; 
import java.io.FileInputStream; 

public class BinaryS 
    { 

    public static void main(String[] args) { 
     Tree randomTree = RandomTreeBuilder.randomTree(10); 

     FileOutputStream fOut=null; 
     ObjectOutputStream oOut=null; 

     try{ 
      fOut= new FileOutputStream("/Users/Pat/programs/binaryfile.txt"); 
      oOut = new ObjectOutputStream(fOut); 
      oOut.writeObject(randomTree); //serializing randomTree 
      System.out.println("An employee is serialized into /Users/Pat/binaryfile.txt"); 
     }catch(IOException e){ 
      e.printStackTrace(); 
     }finally{ 
      try { 
       oOut.flush(); 
       oOut.close(); 
       fOut.close(); 
      } catch (IOException e1) { 
       e1.printStackTrace(); 
      } 
     } 
    } 
}); 

我相信問題是當我使用writeObject(randomTree)。我得到一些終端例外,當這種情況發生......他們都低於:

java.io.NotSerializableException:GeneralTree 在java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1081) 在java.io.ObjectOutputStream中。的writeObject(ObjectOutputStream.java:302) 在BinaryS.main(BinaryS.java:24)

編輯:我知道這說GeneralTree,但在類是在我開始把

print("public class RandomTreeBuilder implements java.io.Serializable"); 

然後,在它下面找到GeneralTree

print(" protected static Tree tree; 
protected static ArrayList names; 
//e6.1 

/** 
*Builds a random tree. The build method does the work. 
*/ 
//b6.2 
public static Tree randomTree(int n) { 
    // Create a random binary tree with n external nodes 
    tree = new GeneralTree(); 
    names = NameGenerator.getNames(); 
    build(tree.getRoot(), n); // auxiliary recursive method 
    return tree; 

「);

更新:嘿傢伙,我想出了我自己的問題,結果我是一個白癡,並沒有意識到我不得不下載一個額外的.java文件,一個簡單的修復吧!謝謝你的幫助!

回答

4

根據猜測,GeneralTree不實施Serializable標記接口,如文檔here所述。

實際上,它也可能是您存儲在樹中的對象不是可序列化的。集合只有在其中的所有元素都是可序列化的情況下才是可序列化的。

0

編輯:我知道這說GeneralTree,但 在類是在一開始我 把

print("public class RandomTreeBuilder implements java.io.Serializable"); 

這對你沒有好 - 你是不是要寫一個對象類型RandomTreeBuilder到對象流;你試圖寫類型是GeneralTree,它是類必須實現Serializable接口


FYI:如果你有沒有碰到過它來了,本文涵蓋了許多序列化的技巧和需要注意的地方:Discover the secrets of the Java Serialization API