2012-04-01 281 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