bordeux
bordeux

Reputation: 622

Add progressbar to BZip2CompressorInputStream

This is my code:

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

How can i add progress bar to extract task, or how can i get the compressed file size?

Upvotes: 1

Views: 532

Answers (2)

Ishu
Ishu

Reputation: 5457

Use the below code few modifications::

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

The only thing left is you have to calulace the total file size

Upvotes: 1

SJuan76
SJuan76

Reputation: 24895

The best way would be:

  1. Add a callback or a listener to your method/class (I prefer a listener list to give it more flexibility).

  2. Calculate the compressed file size (S).

  3. Keep the total amount of bytes read to the moment (B).

  4. For each iteration, report to the callback/listeners of B / S. Let the listeners decide what to do with that data.

Upvotes: 2

Related Questions