作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试从 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));
}
}
最佳答案
我知道这是一个很晚的回复,您可以尝试使用以下实现
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/
我是一名优秀的程序员,十分优秀!