MessagePack Java Jackson 在不关闭输入流(input stream)的情况下反序列化多变量

com.fasterxml.jackson.databind.ObjectMapper 在读取输入流变量的时候默认的将会关闭输入流。

如果你不希望关闭输入流,你可以设置 JsonParser.Feature.AUTO_CLOSE_SOURCE 参数为 false。

本测试方法,可以在 https://github.com/cwiki-us-demo/serialize-deserialize-demo-java/blob/master/src/test/java/com/insight/demo/serialize/MessagePackSerializer.java 中找到。

 

/**
 * 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+Dataformat

posted @   huyuchengus  阅读(417)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2018-08-10 使用 mod_rewrite 来修改 Confluence 6 的 URLs
2018-08-10 Confluence 6 使用 Apache 的 mod_jk
2018-08-10 使用 Apache 来限制访问 Confluence 6 的管理员界面
点击右上角即可分享
微信分享提示