Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add progress bar to zip utility while zipping or extracting in java?

I would like to show progress bar in my swing app, which will zip the selected file. for this process i want to show a progress bar while processing.It may be in a JOptionPane or a given panel as a parameter to utility.

//Select a text file to be zip    
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));


chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
  public boolean accept(File f) {
    return f.getName().toLowerCase().endsWith(".txt")
        || f.isDirectory();
  }

  public String getDescription() {
    return "GIF Images";
  }
});

String source ="";
int r = chooser.showOpenDialog(new JFrame());
if (r == JFileChooser.APPROVE_OPTION) {
   source = chooser.getSelectedFile().getPath();
  File file = chooser.getSelectedFile();

//Start ZIP
try {

        String target = "upload/data-1.zip";
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(target));
        FileInputStream fis = new FileInputStream(file);

        // put a new ZipEntry in the ZipOutputStream
        zos.putNextEntry(new ZipEntry(file.getName()));

        int size = 0;
        byte[] buffer = new byte[1024];
        JProgressBar pb = new JProgressBar();
        pb.setStringPainted(true);
        pb.setIndeterminate(true);

        JPanel panel = new JPanel();
        panel.add(pb);
        JOptionPane.showInputDialog(panel);



        // read data to the end of the source file and write it to the zip
        // output stream.
        while ((size = fis.read(buffer, 0, buffer.length)) > 0) {
                zos.write(buffer, 0, size);
               pb.setValue(size);
               pb.repaint();
               if (size >= file.size) {
                 panel.dispose();
               }
            <<HERE I TRIED TO GIVE PROGRESS ABR VALUE BUT NOT SUCCEDED>>
        }

        zos.closeEntry();
        fis.close();

        // Finish zip process
        zos.close();
        System.out.println("finished");
} catch (IOException e) {
        e.printStackTrace();
}
}
like image 452
itro Avatar asked May 24 '12 15:05

itro


2 Answers

Consider using SwingWorker. You can update UI with intermediate results using process() method. Also, SwingWorker has bound progress property. You can use setProgress() to update it. Then, add PropertyChangeListener to respond to progress property updates.

Check out How to Use Progress Bars. The article demonstrates collaboration of SwingWorker with a progress bar.

like image 149
tenorsax Avatar answered Oct 21 '22 11:10

tenorsax


you can't zip the file on the EventDispatchThread, or your Gui is blocked during the process and you won't see progress in the ProgressBar. Use a SwingWorker.

like image 44
keuleJ Avatar answered Oct 21 '22 09:10

keuleJ