I am trying out google cloud storage; here is my code:
File file = new File("mydir" + "/" + fileName);
Storage.Objects.Get get = storage.objects().get("bucketname", fileName);
FileOutputStream stream = new FileOutputStream(file);
get.executeAndDownloadTo(stream);
stream.flush();
stream.close();
The download is working ( am not getting any error or crush ) I checked that by setting break point and inspecting the file
object. I checked file.exists()
which returns true
and file.length()
which returns 847
byes.
But if I go to my phone and try to access the file I cant find it; also the file I am downloading is a picture file if I try to create a bitmap out of it I always get null.
BitmapFactory.decodeFile(file.getAbsolutePath())
Found a solution; so the issue is with this code:
get.executeAndDownloadTo(stream)
is not downloading the file fully for a reason that I dont know.
Solution: I wrote a simple util method that copies the input stream to output stream byte by byte:
public static void copyStream(InputStream is, OutputStream os) throws Exception {
final int buffer_size = 4096;
byte[] bytes = new byte[buffer_size];
for (int count=0;count!=-1;) {
count = is.read(bytes);
if(count != -1) {
os.write(bytes, 0, count);
}
}
os.flush();
is.close();
os.close();
}
Call:
Utils.copyStream(get.executeMediaAsInputStream(), stream);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.