将进度条添加到BZip2CompressorInputStream

时间:2012-04-01 11:23:17

标签: java android

这是我的代码:

public void extract(String input_f, String output_f){
    int buffersize = 1024;
    FileInputStream in;
    try {
        in = new FileInputStream(input_f);
        FileOutputStream out = new FileOutputStream(output_f);
        BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in);
        final byte[] buffer = new byte[buffersize];
        int n = 0;

        while (-1 != (n = bzIn.read(buffer))) {
            out.write(buffer, 0, n);
        }
        out.close();
        bzIn.close();
        } catch (Exception e) {
        throw new Error(e.getMessage());
    }
}

如何添加进度条以提取任务,或者如何获取压缩文件大小?

2 个答案:

答案 0 :(得分:2)

最好的方法是:

  1. 为您的方法/类添加回调或监听器(我更喜欢监听器列表以提供更大的灵活性)。

  2. 计算压缩文件大小(S)。

  3. 保持读取的总字节数(B)。

  4. 对于每次迭代,向B / S的回调/听众报告。让听众决定如何处理该数据。

答案 1 :(得分:1)

使用以下代码进行少量修改::

public void extract(String input_f, String output_f){
    int buffersize = 1024;
    FileInputStream in;
    try {
        in = new FileInputStream(input_f);
        FileOutputStream out = new FileOutputStream(output_f);
        BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in);
        final byte[] buffer = new byte[buffersize];
        int n = 0;
        int total = 0;

        while (-1 != (n = bzIn.read(buffer))) {
        total += n;
        final int percentage=(int)(total*100/lenghtOfFile); 
        YourActivity.this.runOnUiThread(new Runnable() {
            public void run() {
                // TODO Auto-generated method stub                               
                progressBar.setProgress(percentage);                                 
                }
            });
            out.write(buffer, 0, n);
        }
        out.close();
        bzIn.close();
    } catch (Exception e) {
        throw new Error(e.getMessage());
    }
}

唯一剩下的就是你需要调整总文件大小