首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >作为流访问StringWriter内容

作为流访问StringWriter内容
EN

Stack Overflow用户
提问于 2018-10-26 14:45:30
回答 1查看 268关注 0票数 0

我希望从存储在我的MongoDB中的几个较小的文档中编译一个大型文档为JSON。我已经编写了一个Java函数来编译我的文档,现在我希望我的应用程序能够访问JSON,以便将它返回给客户机,或者对它进行进一步的处理。

我的问题是,实例化JSON字符串会占用大量内存,因此我已经开始运行OutOfMemoryErrors。我从如下所示的toJSON库中实现了自己版本的MongoDB方法:

代码语言:javascript
复制
/**
 * Borrowed from the MongoDB toJSON method for Documents, except we dont instantiate the json string and return the writer instead.
 *
 * @return a buffer containing the JSON representation of the given document
 * @throws org.bson.codecs.configuration.CodecConfigurationException if the registry does not contain a codec for the document values.
 */
private Writer toJson(Document document) {
        JsonWriter writer = new JsonWriter(new StringWriter(), new JsonWriterSettings(true));
        new DocumentCodec().encode(writer, document, EncoderContext.builder().isEncodingCollectibleDocument(true).build());
        return writer.getWriter();
}

此方法不返回字符串,而是返回缓冲JSON字符串的写入器。现在,我想在我的应用程序中使用这个方法,而不调用toString()方法,就像我在网上的许多示例中看到的那样。我找到的最接近的例子是解决方案在本页的底部

代码语言:javascript
复制
try (BufferedWriter bw = new BufferedWriter(new FileWriter("TempFile1mod"))) {
    final int aLength = aSB.length();
    final int aChunk = 1024;// 1 kb buffer to read data from 
    final char[] aChars = new char[aChunk];

    for (int aPosStart = 0; aPosStart < aLength; aPosStart += aChunk) {
    final int aPosEnd = Math.min(aPosStart + aChunk, aLength);
    aSB.getChars(aPosStart, aPosEnd, aChars, 0); // Create no new buffer
    bw.write(aChars, 0, aPosEnd - aPosStart);// This is faster than just copying one byte at the time
    }

这确实可以做我想做的事情,并且允许我将字符串以块的形式写入任何流。但是,由于在我看来,这似乎是一个常见的用例,所以我希望Java有一些通用的方法将数据从字符串缓冲区输送到另一个流中。

我是不是遗漏了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-29 11:34:19

谢谢托马斯的建议。最后,我将我的StringBuffer传递到这样的CharSequenceInputStream中:

代码语言:javascript
复制
/**
 * Borrowed from the MongoDB toJSON method for Documents, except we dont
 * instantiate the JSON String but return an InputStream instead.
 *
 * @return a buffer containing the JSON representation of the given document
 * @throws org.bson.codecs.configuration.CodecConfigurationException if the
 *         registry does not contain a codec for the document values.
 */
private InputStream toJson(Document document) {
    JsonWriter writer = new JsonWriter(new StringWriter(), new JsonWriterSettings(true));

    new DocumentCodec().encode(writer, document,
            EncoderContext.builder().isEncodingCollectibleDocument(true).build());

    CharSequence result = ((StringWriter) writer.getWriter()).getBuffer();

    return new CharSequenceInputStream(result, Charset.forName("UTF-8"));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53011197

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档