MessagePack Java Jackson 在不關閉輸出流(output stream)的狀況下序列化多變量

com.fasterxml.jackson.databind.ObjectMapper 在默認的狀況下在寫出輸入後將會關閉輸出流(output stream)。java

若是你但願序列化多值變量在同一個輸出流的狀況下,你不但願在輸出完一個就關閉輸出流,你能夠設置  JsonGenerator.Feature.AUTO_CLOSE_TARGET 參數爲 Falsegit

本測試方法,能夠在 https://github.com/cwiki-us-demo/serialize-deserialize-demo-java/blob/master/src/test/java/com/insight/demo/serialize/MessagePackSerializer.java 中找到。github

 

/**
 * Serialization Not Close output stream
 */
@Test
public void testMessagePackSerializationNotCloseOutputStream() {
    logger.debug("testMessagePackSerializationNotCloseOutputStream");

    try {
        File tempFile = File.createTempFile("messagepack-", "-cwiki.us");

        OutputStream out = new FileOutputStream(tempFile);
        ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
        objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);

        objectMapper.writeValue(out, 1);
        objectMapper.writeValue(out, "two");
        objectMapper.writeValue(out, 3.14);
        out.close();

        MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new FileInputStream(tempFile));
        System.out.println(unpacker.unpackInt());      // => 1
        System.out.println(unpacker.unpackString());   // => two
        System.out.println(unpacker.unpackFloat());    // => 3.14

        tempFile.deleteOnExit();
    } catch (IOException ex) {
        logger.error("Serialize Error", ex);
    }
}

 

https://www.cwiki.us/display/Serialization/MessagePack+Jackson+Dataformatapp

相關文章
相關標籤/搜索