为了账号安全,请及时绑定邮箱和手机立即绑定

以流的形式访问 StringWriter 内容

以流的形式访问 StringWriter 内容

慕雪6442864 2021-12-10 10:58:39
我想从存储在我的 MongoDB 中的几个较小的文档中将一个大文档编译为 JSON。我已经编写了一个 Java 函数来编译我的文档,现在我希望我的应用程序能够访问 JSON,以便将它返回给客户端,或者对其进行进一步处理。我的问题是实例化 JSON 字符串会占用大量内存,因此我开始遇到 OutOfMemoryErrors。我已经从 MongoDB 库中实现了我自己的 toJSON 方法版本,如下所示:/** * 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() 方法。我找到的最接近的例子是本页底部的解决方案。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 有一些通用的方法来将我的数据从字符串缓冲区中输送到另一个流中。我错过了什么吗?
查看完整描述

1 回答

?
MM们

TA贡献1886条经验 获得超2个赞

我最终将 StringBuffer 传递到CharSequenceInputStream 中,如下所示:


/**

 * 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"));

}


查看完整回答
反对 回复 2021-12-10
  • 1 回答
  • 0 关注
  • 185 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号