2012-04-01 282 views
1

这是我的代码:添加进度进行BZip2CompressorInputStream

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

最好的办法是:

  1. 添加回调或监听到你的方法/类(我喜欢听众列表,给它更多的灵活性)。

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

  3. 保持读出到时刻(B)的总字节量。

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

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()); 
    } 
} 

唯一剩下的是你必须calulace总文件大小

+0

“唯一剩下的就是你必须calulace总文件大小“ 我知道,但”我怎样才能得到压缩文件的大小?“ – bordeux 2012-04-01 12:12:29

+0

什么是input_f和output_f,如果你有输入流,你可以使用InputStream; int lengthofFile = in.available(); – Ishu 2012-04-01 12:15:57

+0

in.available();结果为0。 – bordeux 2012-04-01 18:09:19