GridFS存储GZIPOutputStream

问题描述 投票:0回答:1

我想将文件存储得尽可能小。因此,我决定将json文件压缩。我目前正在使用创建gzip文件,上传mongodb并删除文件夹中文件的方法,但是我注意到gridfs具有将输入流保存到数据库的功能。

我的问题

  1. 我应该使用上面提到的当前订单还是gridfs上传流功能?
  2. 以较小的数据大小制作文件gzip是一个好的解决方案吗?

如果我所有的问题都回答是肯定的。我想知道如何使用GridFS Inputstream并将我的gzip代码转换为gridfs。

当前代码

try {
    GZIPOutputStream gzip = new GZIPOutputStream(new FileOutputStream("pdiskio.dsv"));
    OutputStreamWriter osw = new OutputStreamWriter(gzip, StandardCharsets.UTF_8);
    osw.write(saves.toJSONString());
    osw.close();
} catch (IOException e) {
    e.printStackTrace();
}
database mongodb gzip inputstream gridfs
1个回答
0
投票

经过一些搜索后,我已经学会了如何正确使用它,而又不使用我的文件夹数据。我想与别人分享我的示例代码。

这里是示例代码

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(byteArrayOutputStream);
    gzip.write(saves.toJSONString().getBytes(StandardCharsets.UTF_8));
    gzip.close();

    GridFSBucket gridFSFilesBucket = GridFSBuckets.create(database, "pdisks");
    GridFSUploadOptions options = new GridFSUploadOptions()
            .metadata(new Document("metadataValue", "test-value"));

    InputStream ff = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    ObjectId fileId = gridFSFilesBucket.uploadFromStream(minewatchSaveManager.getId(), ff, options);
© www.soinside.com 2019 - 2024. All rights reserved.