compress file with JProgressBar - Java Swing

Java examples for Swing:JProgressBar

Description

compress file with JProgressBar

Demo Code


//package com.java2s;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.zip.GZIPOutputStream;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

public class Main {
    public static JLabel processLab;

    public static void compress(String file, JProgressBar pbar) {
        //variable definition
        String sourcefile = file;
        File oldfile;/*from  ww w.j av  a2s . c o m*/
        File new_file;
        FileInputStream finStream;
        BufferedInputStream bufinStream;
        FileOutputStream outStream;
        GZIPOutputStream goutStream;
        byte[] buf = new byte[1024];
        int i;
        int inc;

        try {
            oldfile = new File(sourcefile);
            new_file = new File(sourcefile + ".gz");
            finStream = new FileInputStream(oldfile);
            bufinStream = new BufferedInputStream(finStream);
            outStream = new FileOutputStream(new_file);
            goutStream = new GZIPOutputStream(outStream);
            pbar.setMinimum(0);
            pbar.setMaximum((int) oldfile.length());
            inc = (int) (oldfile.length() / 1024);
            processLab
                    .setText("Compressing... "
                            + sourcefile.substring(sourcefile
                                    .lastIndexOf("\\") + 1));
            while ((i = bufinStream.read(buf)) >= 0) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        pbar.setValue(pbar.getValue() + inc);
                    }
                });
                goutStream.write(buf, 0, i);
            }
            pbar.setValue(pbar.getMaximum());
            bufinStream.close();
            goutStream.close();
        } catch (IOException e) {
            System.out.println("Exception is" + e.getMessage());
        }
    }
}

Related Tutorials