【发布时间】:2016-07-10 13:37:57
【问题描述】:
我尝试从 mongodb 下载文件。上传文件的大小是2106字节,chunkSize=2048字节,所以GridFS把文件分成2块。当我执行downloadStream.read(bytesToWriteTo)的代码时,只能读取第一个块的数据,不能读取第二个块的数据。如何读取所有数据?
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));
}
}
【问题讨论】: