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

相关文章
相关标签/搜索