使用box-api进度监听器

问题描述 投票:0回答:1

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

...
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函数。有没有关于如何访问它的例子?我该如何访问它?

java box-api boxapiv2
1个回答
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 ...
    }
});

试试看。希望这会给出一个想法。

© www.soinside.com 2019 - 2024. All rights reserved.