6
GridFSDownloadStream can not read all data
source link: https://www.codesd.com/item/gridfsdownloadstream-can-not-read-all-data.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
GridFSDownloadStream can not read all data
advertisements
I try to download file from mongodb . the size of uploaded file is 2106
bytes,and chunkSize=2048
bytes, so GridFS divides the file into 2 chunks. when I excute the codes of downloadStream.read(bytesToWriteTo)
, only read data of the first chunk, and can not read the data of second chunk. How can I read all of the data?
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));
}
}
I know it is a very late reply, you can try using following implementation
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));
}
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK