2011-03-05 112 views
5

據我所知,Kryo序列化/反序列化發生在每個對象上。是否可以將多個對象序列化爲單個文件?在另一個類似的SO問題中提出的另一種解決方法是使用一組對象。考慮到需要序列化的大量數據,我覺得它不會像應該那樣高效。這是正確的假設嗎?使用Kryo將多個對象序列化爲單個文件

回答

2

Kryo API是否需要OutputStream?如果是這樣,給它提供相同的OutputStream來序列化多個文件。閱讀時用InputStream做同樣的事情。一個好的序列化格式將有長度編碼或終止符號,並且不會依賴於EOF。

只要所有這些對象已經在內存中,數組方法也可以以最小的開銷工作。你正在談論的是爲每個對象添加幾個字節來創建一個數組來保存它們。如果它們不全在內存中,則必須首先將它們全部加載到內存中以在它們周圍創建一個數組。鑑於足夠大的數據集,這肯定會成爲一個問題。

+0

序列化/反序列化期間的緩衝區/流嚴格映射到類。上述方法可能無法正常工作。讓我嘗試。 – 2011-03-09 00:34:29

+0

對象不在內存中。所以陣列的方法將是一個問題 – 2011-03-09 00:35:20

+3

這個答案是正確的,Kryo v2支持流式傳輸。將對象依次寫入文件。從文件中逐一閱讀。 – NateS 2012-06-15 02:47:06

1

由於Kryo支持流式傳輸,所以沒有什麼可以阻止你在頂層寫入/讀取多個對象給kryo。例如,以下程序將兩個不相關的對象寫入文件,然後再將它們反序列化:

public class TestClass{ 


    public static void main(String[] args) throws FileNotFoundException{ 
     serialize(); 
     deSerialize(); 
    } 

    public static void serialize() throws FileNotFoundException{ 
     Collection<String>collection=new ArrayList<>(); 
     int otherData=12; 


     collection.add("This is a serialized collection of strings"); 

     Kryo kryo = new Kryo(); 
     Output output = new Output(new FileOutputStream("testfile")); 
     kryo.writeClassAndObject(output, collection); 
     kryo.writeClassAndObject(output, otherData); //we could add as many of these as we like 
     output.close(); 
    } 

    public static void deSerialize() throws FileNotFoundException{ 
     Collection<String>collection; 
     int otherData; 

     Kryo kryo = new Kryo(); 
     Input input = new Input(new FileInputStream("testfile")); 
     collection=(Collection<String>)kryo.readClassAndObject(input); 
     otherData=(Integer)kryo.readClassAndObject(input); 

     input.close(); 

     for(String string: collection){ 
      System.out.println(string); 
     } 

     System.out.println("There are other things too! like; " + otherData); 

    } 


} 
相關問題