使用box-api进度监听器

时间:2019-03-21 04:38:04

标签: java box-api boxapiv2

我正在尝试使用here中所述的Box API应用程序从其下载功能下载文件。

...
FileOutputStream stream = new FileOutputStream(info.getName());
// Provide a ProgressListener to monitor the progress of the download.
file.download(stream, new ProgressListener() {
   public void onProgressChanged(long numBytes, long totalBytes) {
    double percentComplete = numBytes / totalBytes;
 }
});
....

但是,我无法使用onProgessChanged函数。是否有有关如何访问它的示例?如何访问?

1 个答案:

答案 0 :(得分:0)

这只是一种解决方法。通过扩展超类ProgressOutputStream创建一个类OutputStream

public class ProgressOutputStream extends OutputStream {

        public ProgressOutputStream(long totalFileSize, OutputStream stream, Listener listener) {
            this.stream = stream;
            this.listener = listener;
            this.completed = 0;
            this.totalFileSize = totalFileSize;
        }

        @Override
        public void write(byte[] data, int off, int length) throws IOException {
            this.stream.write(data, off, length);
            track(length);
        }

        @Override
        public void write(byte[] data) throws IOException {
            this.stream.write(data);
            track(data.length);
        }

        @Override
        public void write(int c) {
            this.stream.write(c);
            track(1)
        }

        private void track(int length) {
            this.completed += length;
            this.listener.progress(this.completed, this.totalFileSize);
        }

        public interface Listener {
            public void progress(long completed, long totalFileSize);
        }
    }

在您的ProgressOutputStream中呼叫file.download(),例如:

FileOutputStream stream = new FileOutputStream(info.getName());
file.download(new ProgressOutputStream(size, stream, new ProgressOutputStream.Listener() {
    void progress(long completed, long totalFileSize) {
        // update progress bar here ...
    }
});

尝试一下。希望这会给您一个想法。