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

 

 

Using the ZIP file streams is relatively simple. Each file within the ZIP file has a header with information including the name of the file and the compression method that was used.

Using the ZipInputStream Class

You use a ZipInputStream to read a ZIP file.  Each file within the ZIP file is represented by a ZipEntry.

Here's an example of how to read a ZIP file using ZipInputStream and ZipEntry:

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.InputStreamReader;
import java.io.IOException;

import java.util.zip.ZipInputStream;
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 ReadZipFile 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
    } 
    
    ReadZipFile frame = new ReadZipFile();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
  
  /**
   *   Constructor.
   */
  public ReadZipFile()
  {
    setTitle("ZIP File Reader");
      
    // 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(ReadZipFile.this);
      if (ret == JFileChooser.APPROVE_OPTION)
      {
        m_zipFileName = chooser.getSelectedFile().getPath();
        scanZipFile(m_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();
    ZipInputStream zin = null;
    ZipEntry entry = null;
    try
    {
      zin = new ZipInputStream( new FileInputStream(zipFileName) );
      while ( (entry = zin.getNextEntry()) != null )
      {
        m_fileList.addItem(entry.getName());
        zin.closeEntry();
      }
      m_zipFileName = zipFileName;
    }
    catch (IOException ioe)
    {
      ioe.printStackTrace();
    }
    finally
    {
      try
      {
        zin.close();
      } 
      catch (IOException ex)
      {
        // Ignore
      }
    }
  }
  
  /**
   *   Displays the files within the ZIP file,
   *   in the List component.
   */
  private void loadZipFile(String name)
  {
    ZipInputStream zin = null;
    ZipEntry entry = null;
    try
    {
      // Open the Zip file stream
      zin = new ZipInputStream( new FileInputStream(m_zipFileName) );
      // Scan through the entries until we find the one that matches
      while ( (entry = zin.getNextEntry()) != null)
      {
        // Does the name match?
        if (entry.getName().equals(name))
        {
          // Read the entry into the text area
          BufferedReader in = new BufferedReader( new InputStreamReader(zin) );
          String line;
          while ( (line = in.readLine()) != null)
          {
            m_fileText.append(line);
            m_fileText.append("\n");
          }
          // Be sure to show the start of the file, after loading.
          m_fileText.setCaretPosition(0);
        }
        zin.closeEntry();
      }
    }
    catch (IOException ioe)
    {
      ioe.printStackTrace();
    }
    finally
    {
      try
      {
        if (zin != null)
          zin.close();
      } 
      catch (IOException ex)
      {
        // Ignore
      }
    }
  }
  
  /////// Private data /////////
  
  private JComboBox m_fileList = new JComboBox();
  private JTextArea m_fileText = new JTextArea(30, 80);
  private String    m_zipFileName;
}

The above class uses a FileFilter for the FileChooser dialog:

package inputOutput;

import java.io.File;
import java.util.ArrayList;
import javax.swing.filechooser.FileFilter;

/**
 * Class to provide a file filter based on one or more
 * extensions (file types)
 *
 */
public class TypeFileFilter extends FileFilter
{
  /**
   * Creates a new instance of TypeFileFilter
   * for a single file type
   */
  public TypeFileFilter(String type)
  {
    addType(type);
  }

  /**
   * Adds a new file type to the filter
   */
  public void addType(String type)
  {
    if (!type.startsWith("."))
      type = "." + type;
    m_types.add(type.toLowerCase());
  }
  
  /**
   * Returns true if the file passes muster,
   * false otherwise.
   */
  public boolean accept(File file)
  {
    if (file.isDirectory())
      return true;
    String name = file.getName().toLowerCase();
    for (String type: m_types)
    {
      if (name.endsWith(type))
        return true;
    }
    return false;
  }

  /**
   * Returns a description for the file set that 
   * this file filter recognizes
   */
  public String getDescription()
  {
    return m_description;
  }
  
  /**
   * Sets a description for the file set that this
   * file filter recognizes.
   */
  public void setDescription(String description)
  {
    m_description = description;
  }
  
  ////// Private data //////
  
  // Holds the types that are to be matched.
  private ArrayList<String> m_types = new ArrayList<String>();
  private String m_description = "";
}

After you run this ReadZipFile class, and open a ZIP file, it produces something that looks like this (I opened the Java 5/1.5 src.zip file, and selected the java.lang.String class to display).

If you select a different entry in the combo box at the bottom of the frame, it will display the contents of that file (assuming it to be a text file).

 

The page was last updated February 19, 2008