Home : Course Map : Chapter 9 : Java : Supplements :
ZIP/GZIP Compression and Decompression:
Demo
JavaTech
Course Map
Chapter 9

Introduction
Overview
Streams
Wrappers,Buffers
Console I/O
  Text Output 
     Demo 1

  Formatter/printf()
     Demo 2

  Tex 2t Input
     Demo 3

  Scanner
     
Demo 4
File Class
  File I/O
  File Output-Text
     Demo 5

  Formatter to File
     Demo 6

  File Input - Text
    Demo 7

  Scanner - Files
     Demo 8

  File I/O - Binary
     Demo 9
   Demo 10
File Chooser Dialog
  Demo 11

Character Codes
  Demo 12
   Demo13
Object I/O
Types to Bytes
Stream Filters
Other I/O Topics
Exercises

    Supplements
Character I/O
  Demo 1   Demo 2
Random Access
  Demo 3
ZIP/GZIP Streams
  Demo 4
Piped Streams
  Demo 5
NIO Framework
More NIO
  Demo 6

     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

The application program listed below demonstrates the ZIP and GZIP tools in the java.util.zip package. The program creates a GUI in which the user selects a file for compression or decompression. The user can also choose an output directory for where compressed or decompressed files will be sent.

Note that this program only allows for the compression of a single file at a time. The ZIP process, howerver, can create archive files that hold multiple compressed files and directories. It's left to the reader to modify this program to allow the user to select and compress multiple files.

The program uses the static methods from the ZipGzipper utility class described in the previous page for the compression and decompression tasks. The class implements the Outputable interface to provide for print methods that send messages to the text area to show the history of the user's actions.


ZipGzipApp.java
+ ZipGzipper.java + Outputable.java


Here the File drop down menu allows the user to select the input file or to
select an directory for sending the compressed or decompressed output.


If an archive file (i.e. a file ending in ".zip" or ".gz") is chosen, then the
buttons become controls to decompress the file according to the type.

// Start from StartJApp4.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

/**
  * This class allows the user to compress
  * files into either ZIP or GZIP archives. It
  * also provides for decompression of ZIP and
  * GZIP archives.
  *
  * The interface provides a frame with a menubar
  * and a File drop down menu. The user selects
  * the "Input File" item to open a file chooser to select
  * the file to compress or an archive to decompress. The
  * output directory is chosen via the dropdown menu as
  * well. The default output directory is that of the
  * input file.
  *
  * Two buttons on the control panel, "Zip" and "Gzip"
  * allow the user to select the desired operation.
  * The program examines the suffix of the
  * file determine if it is an archive file. If it is
  * the button operation is indicated with "Unzip" and
  * "Gunzip" labels.
  *
  * The class implements the Outputable interface. Th
  * Messages at each step are sent to a text area with print()
  * and println() methods.
 **/
public class ZipGzipApp extends JFrame
                        implements ActionListener, Outputable
{

  JMenuItem fMenuInput;
  JMenuItem fMenuOutput;
  JMenuItem fMenuClose;

  JTextArea  fTextArea;
  JTextField fInputFileField;
  JTextField fOutputDirField;

  JButton fButtonZip;
  JButton fButtonGzip;

  File fInputFile;
  File fOutputDir;

  // Filter and File object for fFile chooser
  ZipGzipFilter fZipGzipFilter = new ZipGzipFilter ();

  // Create frame and display it.
  public static void main (String [] args) {
      // Can pass frame title in command line arguments
    String title="Compress/Decompress Files";
      if ( args.length != 0) title = args[0];
    ZipGzipApp f = new ZipGzipApp (title);
    f.setVisible (true);
  }

  /**
    * Build the user interface in the constructor.
    * Pass a title to the frame via the constructor argument.
   **/
  ZipGzipApp (String title) {
    super (title);

    // Start with a text area in the center..
    setLayout (new BorderLayout ());
    fTextArea = new JTextArea ("");
    add (fTextArea, "Center");

    // Create a panel with two textfields and labels
    // for the in and out files
    fInputFileField  = new JTextField ();
    fOutputDirField  = new JTextField ();

    JLabel  input_label =
     new JLabel ("Input File:", SwingConstants.RIGHT);
    JLabel output_label =
      new JLabel ("Output Dir:", SwingConstants.RIGHT);

    JPanel label_panel = new JPanel (new GridLayout (2,1));
    label_panel.add (input_label);
    label_panel.add (output_label);

    JPanel fields_panel = new JPanel (new GridLayout (2,1));
    fields_panel.add (fInputFileField);
    fields_panel.add (fOutputDirField);

    JPanel files_panel = new JPanel (new BorderLayout ());
    files_panel.add (label_panel, BorderLayout.WEST);
    files_panel.add (fields_panel, BorderLayout.CENTER);

    // Create a panel with the two buttons
    fButtonZip  = new JButton ("Zip");
    fButtonGzip = new JButton ("Gzip");
    fButtonZip.addActionListener (this);
    fButtonGzip.addActionListener (this);
    JPanel button_panel = new JPanel ();
    button_panel.add (fButtonZip);
    button_panel.add (fButtonGzip);

    JPanel controls_panel = new JPanel (new GridLayout (2,1));
    controls_panel.add (files_panel);
    controls_panel.add (button_panel);

    add (controls_panel, "South");

    // Use the helper method makeMenuItem for making
    // the menu items and registering their listener.
    JMenu m = new JMenu ("File");

    // *** Modify task names to something relevant to
    // the particular program.
    m.add (fMenuInput  = makeMenuItem ("Input file"));
    m.add (fMenuOutput = makeMenuItem ("Output Directory"));
    m.add (fMenuClose  = makeMenuItem ("Quit"));

    JMenuBar mb = new JMenuBar ();
    mb.add (m);

    setJMenuBar (mb);
    setSize (400,400);
    setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);

  } // ctor

  /**
    * Process events from the frame menu and the chooser.
    * Send progress messages to the text area via the println()
    * method.
   **/
  public void actionPerformed (ActionEvent e) {
    boolean status = false;
    int result = 0;

    String command = e.getActionCommand ();

    if (command.equals ("Zip")) {
      if (fInputFile != null && fInputFile.exists ()) {
        // Zip the file
        println ("Zip " + fInputFile.getName ());
        result = ZipGzipper.zipFile (fInputFile, fOutputDir);
        println ("Zip result: " + ZipGzipper.getStatusMessage (result));
      } else {
        println ("Zip failed: No input file!");
      }
    } else
    if (command.equals ("Unzip")) {

      if (fInputFile != null && fInputFile.exists ()) {
         // Unzip the file
         println ("Unzip " + fInputFile.getName ());
         result = ZipGzipper.unzipFile (fInputFile, fOutputDir);
         println ("Unzip result: " +
                    ZipGzipper.getStatusMessage (result));
      } else {
        println ("Unzip failed: No input file!");
      }

    } else
    if (command.equals ("Gzip")) {
      if (fInputFile != null && fInputFile.exists ()) {
         // Gzip the file
         println ("Gzip " + fInputFile.getName ());
         result = ZipGzipper.gzipFile (fInputFile, fOutputDir);
         println ("Gzip result: " +
                    ZipGzipper.getStatusMessage (result));
      } else {
        println ("Gzip failed: No input file!");
      }

    } else
    if (command.equals ("Gunzip")) {

      if (fInputFile != null && fInputFile.exists ()) {
         // Gunzip the file
         println ("Gunzip " + fInputFile.getName ());
         result = ZipGzipper.gunzipFile (fInputFile, fOutputDir);
         println ("Gunzip result: " +
                    ZipGzipper.getStatusMessage (result));
      } else {
        println ("Gunzip failed: No input file!");
      }

    } else
    if (command.equals ("Input file")) {
      // Select the input file
      status = getInputFile ();
      if (!status) {
          println ("No input file chosen!");
          return;
      }

      // Set up buttons according to the type of input file
      String input_file_name = fInputFile.toString ().toLowerCase ();
      if (input_file_name.endsWith(".zip")) {
          fButtonZip.setEnabled (true);
          fButtonZip.setText ("Unzip");
          fButtonGzip.setEnabled (false);
      } else
      if (input_file_name.endsWith(".gz")) {
          fButtonZip.setEnabled (false);
          fButtonGzip.setEnabled (true);
          fButtonGzip.setText ("Gunzip");
      } else {
          fButtonZip.setEnabled (true);
          fButtonGzip.setEnabled (true);
          fButtonZip.setText ("Zip");
          fButtonGzip.setText ("Gzip");
      }

    } else
    if (command.equals ("Output Directory")) {
      // Select the directory for the output.
      status = getOutputDir ();
      if (!status)
          println ("No output directory chosen!");
          return;

    } else
    if (command.equals ("Quit")) {
      dispose ();
    }

  } // actionPerformed

  /**
    * This "helper method" makes a menu item and then
    * registers this object as a listener to it.
   **/
  private JMenuItem makeMenuItem (String name) {
    JMenuItem m = new JMenuItem ( name );
    m.addActionListener ( this );
    return m;
  }

  /**
    * Use a JFileChooser in Open mode to select files
    * to open. Use an instance of ZipGzipFilter to select
    * for *.zip and and *.gz files. If a file is selected then
    * put its path name in the input file text field. Also, use
    * the directory of the file as the default output directory
    * and so put its name in the output text field.
   **/
  boolean getInputFile () {

    JFileChooser fc = new JFileChooser ();
    fc.setDialogTitle ("Choose Input File");

    // Choose only fFiles, not directories
    fc.setFileSelectionMode (JFileChooser.FILES_ONLY);

    // Start in current directory
    fc.setCurrentDirectory (new File ("."));

    // Set filter for zip, gzip, and all files.
    fc.setFileFilter (fZipGzipFilter);

    // Now open chooser
    int result = fc.showOpenDialog (this);

    if (result == JFileChooser.CANCEL_OPTION) {
        return true;
    } else if ( result == JFileChooser.APPROVE_OPTION) {
        fInputFile = fc.getSelectedFile ();
        if (fInputFile != null) {
           println ("Input file found!");
           try {
             fInputFileField.setText (fInputFile.getCanonicalPath ());
             fOutputDir = fInputFile.getParentFile ();
             fOutputDirField.setText (fOutputDir.getCanonicalPath ());
           } catch (Exception e) {
             println ("Unable to determine output file path!");
             return false;
           }
        } else
           return false;

    } else {
        return false;
    }
      return true;

  } // openfFile


  /**
    * Use a JFileChooser  to select a directory to where the
    * output should go. Put the path name of the selected directory
    * in the output directory text field.
   **/
  boolean getOutputDir () {

    JFileChooser fc = new JFileChooser ();
    fc.setDialogTitle ("Choose Output Directory");

    // Start in current directory
    fc.setCurrentDirectory (new File ("."));

    // Choose only directories only.
    fc.setFileSelectionMode (JFileChooser.DIRECTORIES_ONLY);

    // Open chooser dialog
    int result = fc.showSaveDialog (this);

    if ( result == JFileChooser.CANCEL_OPTION) {
        return true;
    } else if (result == JFileChooser.APPROVE_OPTION) {
      fOutputDir = fc.getSelectedFile ();
      try {
         fOutputDirField.setText (fOutputDir.getCanonicalPath ());
      } catch (Exception e) {
        println ("Unable to determine output file path!");
        return false;
      }
      return true;
    } else {
      return false;
    }
  } // saveFile


  /** Implement the Outputable interface. Overried println() with
    * a method to display a string + carriage return on the JTextArea.
   **/
  public void println(String str) {
    fTextArea.append(str + CR);
  }

  /** Implement the Outputable interface. Overried print() with
    * a method to display a string on the JTextArea.
   **/
  public void print(String str) {
    fTextArea.append(str);
  }

} // class ZipGZipApp


/**
  * Class to use with JFileChooser for selecting zip/gzip fFiles.
 **/
class ZipGzipFilter extends javax.swing.filechooser.FileFilter {

  public boolean accept (File f) {
    String name = f.getName ().toLowerCase ();
    return name.endsWith (".zip")
        || name.endsWith (".gz")
        || f.isDirectory ();
  }
  public String getDescription () {
    return "Compressed files  (*.zip, *.gz)";
  }
} // class ZipGzipFilter

 

References & Web Resources

 

Most recent update: July 7, 2005

              Tech
Histogram I/O
Hist I/O - Get/Set
  Demo 1
Hist I/O - Objects
  Demo 2
HistogramStream
  Demo 3
Filtering Data
  Demo 4
Exercises

           Physics
Physics Model
Simulation Design
Physics Simulator
  Demo 1
Experiment Design
Experiment Sim.
  Demo 2
Analysis
Expt. + Analysis
  Demo 3
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.