Class ZipFile
Home ] Up ] Zip File Streams ] Classes ZipInputStream & ZipEntry ] [ Class ZipFile ] Jar File Streams ] Classes JarFile and JarEntry ]

 

 

Using the ZipFile Class

There is also a ZipFile class that allows you to access the ZIP file entries directly, rather than having to scan through the entire ZIP file sequentially.

It is likely that using the ZipFile class in place of the ZipInputStream class could provide better performance.

Here's the same program as above, but with the ZipInputStream replaced by ZipFile.  It simplifies the code, and appears to improve performance -- at least, on my machine:

package inputOutput;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Enumeration;

import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;

/**
 *   Class to open a ZIP file, and display a list of files
 *   stored within it.
 *   When the user selects a ZIP file, the contents of the
 *   file (assumed to be text) are displayed in the text
 *   area.
 *
 *   @author Bryan J. Higgs, 19 September, 1999
 */
public class ReadZipFile2 extends JFrame
{
  /**
   *   Main entry point.
   */
  public static void main(String[] args)
  {
    try
    {
      // Set the system look and feel
      UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
    } 
    catch (Exception ex)
    {
      // Ignore
    } 
    
    ReadZipFile2 frame = new ReadZipFile2();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
  
  /**
   *   Constructor.
   */
  public ReadZipFile2()
  {
    setTitle("ZIP File Reader 2");
      
    // Set up frame menus
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    
    JMenu fileMenu = new JMenu("File");
    menuBar.add(fileMenu);
    
    JMenuItem openItem = new JMenuItem("Open");
    fileMenu.add(openItem);
    openItem.addActionListener( new OpenAction() );
    
    JMenuItem exitItem = new JMenuItem("Exit");
    fileMenu.add(exitItem);
    exitItem.addActionListener( new ActionListener()
      {
        public void actionPerformed(ActionEvent event)
        {
          System.exit(0);
        }
      }
    );
    
    // Set the size of the combo box, and
    // hook it up to its actions
    m_fileList.setEditable(false);
    m_fileList.addItem("Use File->Open to select ZIP file");
    m_fileList.addActionListener( new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        String item = (String) m_fileList.getSelectedItem();
        if (item != null)
          loadZipFile(item);
      }
    }
    );
    m_fileText.setEditable(false);
    m_fileText.setBackground(Color.WHITE);
    
    add(m_fileList, BorderLayout.SOUTH);
    add(new JScrollPane(m_fileText), BorderLayout.CENTER);
    pack();
  }
  
  /**
   *   Inner class to handle open file events.
   */
  private class OpenAction implements ActionListener
  {
    public void actionPerformed(ActionEvent event)
    {
      JFileChooser chooser = new JFileChooser();
      chooser.setCurrentDirectory( new File(".") );
      TypeFileFilter filter = new TypeFileFilter(".zip");
      filter.setDescription("ZIP files");
      chooser.setFileFilter(filter);
      int ret = chooser.showOpenDialog(ReadZipFile2.this);
      if (ret == JFileChooser.APPROVE_OPTION)
      {
        String zipFileName = chooser.getSelectedFile().getPath();
        scanZipFile(zipFileName);
      }
    }
  }
  
  /**
   * Scans the ZIP file and populates the combo box.
   */
  public void scanZipFile(String zipFileName)
  {
    // Clean out the list, in case it's already in use.
    m_fileList.removeAllItems();
    
    ZipEntry entry = null;
    try
    {
      // Close any previous zip file that
      // might have been open.
      if (m_zipFile != null)
      {
        m_zipFile.close();
        m_zipFile = null;
      }
      // Open the new Zip file
      m_zipFile = new ZipFile(zipFileName);
      // Go through all the entries and
      // populate the fileList combo box.
      Enumeration en = m_zipFile.entries();
      while (en.hasMoreElements())
      {
        entry = (ZipEntry)en.nextElement();
        m_fileList.addItem(entry.getName());
      }
    }
    catch (IOException ioe)
    {
      ioe.printStackTrace();
    }
  }
  
  /**
   *   Displays the files within the ZIP file,
   *   in the List component.
   */
  private void loadZipFile(String name)
  {
    InputStream in = null;
    try
    {
      // Get the Zip entry from the already open ZipFile
      ZipEntry entry = m_zipFile.getEntry(name);
      if (entry != null)
      {
        // Populate the text area with the contents of the entry.
        m_fileText.setText("");
        in = m_zipFile.getInputStream(entry);
        BufferedReader reader = 
                    new BufferedReader(
                            new InputStreamReader(in));
        String line;
        while ( (line = reader.readLine()) != null )
        {
          m_fileText.append(line + "\n");
        }
      }
    }
    catch (IOException ioe)
    {
      ioe.printStackTrace();
    }
    finally
    {
      try
      {
        if (in != null)
          in.close();
      } 
      catch (IOException ex)
      {
        // Ignore
      }
    }
  }
  
  /////// Private data /////////
  
  private JComboBox m_fileList = new JComboBox();
  private JTextArea m_fileText = new JTextArea(30, 80);
  private ZipFile   m_zipFile;
}

It produces the same results as the earlier ReadZipFile program, but with better performance when opening an entry in the file.

 

The page was last updated February 19, 2008