gpt4 book ai didi

java - GridFSDownloadStream无法读取所有数据

转载 作者:行者123 更新时间:2023-12-01 10:10:04 25 4
gpt4 key购买 nike

我尝试从 mongodb 下载文件。上传文件的大小为 2106 字节,chunkSize=2048 字节,因此 GridFS 将文件分为 2 个 block 。当我执行downloadStream.read(bytesToWriteTo)代码时,只能读取第一个 block 的数据,无法读取第二个 block 的数据。如何读取所有数据?

public class OpenDownloadStreamDemo {

public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("demo");
GridFSBucket gridFSBucket = GridFSBuckets[enter image description here][1].create(mongoDatabase);
ObjectId fileId = new ObjectId("56f25a8b163b4598987b666b");
GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId);
int fileLength = (int) downloadStream.getGridFSFile().getLength();
byte[] bytesToWriteTo = new byte[fileLength];
downloadStream.read(bytesToWriteTo);
downloadStream.close();
System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));
}
}

The files Collection

The chunks Collection

最佳答案

我知道这是一个很晚的回复,您可以尝试使用以下实现

public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("demo");
GridFSBucket gridFSBucket = GridFSBuckets.create(mongoDatabase);
ObjectId fileId = new ObjectId("56f25a8b163b4598987b666b");
GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int data = downloadStream.read();
while (data >= 0) {
outputStream.write((char) data);
data = downloadStream.read();
}
byte[] bytesToWriteTo = outputStream.toByteArray();
downloadStream.close();
System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));
}
}

关于java - GridFSDownloadStream无法读取所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36175190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com