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

com.fasterxml.jackson.databind.ObjectMapper 在讀取輸入流變量的時候默認的將會關閉輸入流。java

若是你不但願關閉輸入流,你能夠設置 JsonParser.Feature.AUTO_CLOSE_SOURCE 參數爲 false。git

本測試方法,能夠在 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 input stream
 */
@Test
public void testMessagePackSerializationNotCloseInputStream() {
    logger.debug("testMessagePackSerializationNotCloseInputStream");

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

        MessagePacker packer = MessagePack.newDefaultPacker(new FileOutputStream(tempFile));
        packer.packInt(42);
        packer.packString("Hello");
        packer.close();

        FileInputStream in = new FileInputStream(tempFile);
        ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
        objectMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
        System.out.println(objectMapper.readValue(in, Integer.class));
        System.out.println(objectMapper.readValue(in, String.class));
        in.close();

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

 

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

相關文章
相關標籤/搜索