如何在java中压缩或解压缩时将进度条添加到zip实用程序?

时间:2012-05-24 15:58:37

标签: java swing zip progress-bar unzip

我想在我的swing应用中显示进度条,它会压缩所选文件。 对于这个过程,我想在处理时显示进度条。它可能在JOptionPane或给定面板中作为实用程序的参数。

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

2 个答案:

答案 0 :(得分:5)

考虑使用SwingWorker。您可以使用process()方法使用中间结果更新UI。此外,SwingWorker已绑定progress属性。您可以使用setProgress()进行更新。然后,添加PropertyChangeListener以响应progress属性更新。

结帐How to Use Progress Bars。本文演示了SwingWorker与进度条的协作。

答案 1 :(得分:2)

您无法在EventDispatchThread上压缩文件,或者您的Gui在此过程中被阻止,您将无法在ProgressBar中看到进度。使用SwingWorker。