我正在使用this method从Google云端硬盘下载文件。
我的代码:
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();
有没有办法获得文件下载的进度?
答案 0 :(得分:2)
回答我自己的问题,发现它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);
答案 1 :(得分:0)
我能想到的第一件事是将FileOutputStream包装在一个自定义Stream中,该Stream会覆盖write方法,以另外通知侦听器写入的字节数。像这样:
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);
}
其余的是知道文件的大小,以便您可以计算进度监听器中百分比的进度。