簡體   English   中英

使用Kryo將多個對象序列化為單個文件

[英]Serialize multiple objects into a single file using Kryo

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

由於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);

    }


}

Kryo API是否采用OutputStream? 如果是這樣,只需輸入相同的OutputStream來序列化多個文件。 讀取時對InputStream執行相同操作。 良好的序列化格式將具有長度編碼或終止符號,並且不會依賴於EOF。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM