问题
I'm using this method to download a file from Google Drive.
My code:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
driveService.files().export(remoteFiles[0].getId(),"text/plain").executeMediaAndDownloadTo(byteArrayOutputStream);
FileOutputStream fileOutputStream= new FileOutputStream(new File(downloadsDirectory,remoteFiles[0].getName()));
byteArrayOutputStream.writeTo(fileOutputStream);
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
fileOutputStream.close();
Is there a way to get the progress of the file download?
回答1:
Answering my own question,found it on this page.
//custom listener for download progress
class DownloadProgressListener implements MediaHttpDownloaderProgressListener{
@Override
public void progressChanged(MediaHttpDownloader downloader) throws IOException {
switch (downloader.getDownloadState()){
//Called when file is still downloading
//ONLY CALLED AFTER A CHUNK HAS DOWNLOADED,SO SET APPROPRIATE CHUNK SIZE
case MEDIA_IN_PROGRESS:
//Add code for showing progress
break;
//Called after download is complete
case MEDIA_COMPLETE:
//Add code for download completion
break;
}
}
}
//create a Drive.Files.Get object,
//set a ProgressListener
//change chunksize(default chunksize seems absurdly high)
Drive.Files.Get request = driveService.files().get(remoteFiles[0].getId());
request.getMediaHttpDownloader().setProgressListener(new DownloadProgressListener()).setChunkSize(1000000);
request.executeMediaAndDownloadTo(outputStream);
回答2:
The first thing that I can think of is wrapping the FileOutputStream in a custom Stream that overrides the write method to additionally notify a listener for the amount of bytes written. Like this:
public class ProgressOutputStream extends OutputStream {
IProgressListener _listener;
OutputStream _stream;
int _position;
public ProgressOutputStream(OutputStream stream, IProgressListener listener) {
_stream = stream;
_listener = listener;
}
@Override
public void write(byte[] b, int offset, int len) {
_stream.write(b, offset, len);
_position += len;
reportProgress();
}
private void reportProgress() {
_listener.onProgressUpdate(_position);
}
@Override
public void write(int b) {
_stream.write(b);
}
}
interface IProgressListener {
void onProgressUpdate(int progress);
}
The rest is to know the size of the file so that you can calculate the progress in percentages in your progress listener.
来源:https://stackoverflow.com/questions/39369580/how-to-get-progress-of-a-file-being-downloaded-from-google-drive-using-rest-api