A frame with a text area to show the contents of a file inside a ZIP archive : Zip Tar File « File Input Output « Java





A frame with a text area to show the contents of a file inside a ZIP archive

   
/*
   This program is a part of the companion code for Core Java 8th ed.
   (http://horstmann.com/corejava)

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

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.SwingWorker;

/**
 * @version 1.32 2007-06-22
 * @author Cay Horstmann
 */
public class ZipTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(new Runnable()
         {
            public void run()
            {
               ZipTestFrame frame = new ZipTestFrame();
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               frame.setVisible(true);
            }
         });
   }
}

/**
 * A frame with a text area to show the contents of a file inside a ZIP archive, a combo box to
 * select different files in the archive, and a menu to load a new archive.
 */
class ZipTestFrame extends JFrame
{
   public ZipTestFrame()
   {
      setTitle("ZipTest");
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

      // add the menu and the Open and Exit menu items
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("File");

      JMenuItem openItem = new JMenuItem("Open");
      menu.add(openItem);
      openItem.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               JFileChooser chooser = new JFileChooser();
               chooser.setCurrentDirectory(new File("."));
               int r = chooser.showOpenDialog(ZipTestFrame.this);
               if (r == JFileChooser.APPROVE_OPTION)
               {
                  zipname = chooser.getSelectedFile().getPath();
                  fileCombo.removeAllItems();
                  scanZipFile();
               }
            }
         });

      JMenuItem exitItem = new JMenuItem("Exit");
      menu.add(exitItem);
      exitItem.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               System.exit(0);
            }
         });

      menuBar.add(menu);
      setJMenuBar(menuBar);

      // add the text area and combo box
      fileText = new JTextArea();
      fileCombo = new JComboBox();
      fileCombo.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               loadZipFile((String) fileCombo.getSelectedItem());
            }
         });

      add(fileCombo, BorderLayout.SOUTH);
      add(new JScrollPane(fileText), BorderLayout.CENTER);
   }

   /**
    * Scans the contents of the ZIP archive and populates the combo box.
    */
   public void scanZipFile()
   {
      new SwingWorker<Void, String>()
         {
            protected Void doInBackground() throws Exception
            {
               ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
               ZipEntry entry;
               while ((entry = zin.getNextEntry()) != null)
               {
                  publish(entry.getName());
                  zin.closeEntry();
               }
               zin.close();
               return null;
            }

            protected void process(List<String> names)
            {
               for (String name : names)
                  fileCombo.addItem(name);

            }
         }.execute();
   }

   /**
    * Loads a file from the ZIP archive into the text area
    * @param name the name of the file in the archive
    */
   public void loadZipFile(final String name)
   {
      fileCombo.setEnabled(false);
      fileText.setText("");
      new SwingWorker<Void, Void>()
         {
            protected Void doInBackground() throws Exception
            {
               try
               {
                  ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
                  ZipEntry entry;

                  // find entry with matching name in archive
                  while ((entry = zin.getNextEntry()) != null)
                  {
                     if (entry.getName().equals(name))
                     {
                        // read entry into text area
                        Scanner in = new Scanner(zin);
                        while (in.hasNextLine())
                        {
                           fileText.append(in.nextLine());
                           fileText.append("\n");
                        }
                     }
                     zin.closeEntry();
                  }
                  zin.close();
               }
               catch (IOException e)
               {
                  e.printStackTrace();
               }
               return null;
            }

            protected void done()
            {
               fileCombo.setEnabled(true);
            }
         }.execute();
   }

   public static final int DEFAULT_WIDTH = 400;
   public static final int DEFAULT_HEIGHT = 300;

   private JComboBox fileCombo;
   private JTextArea fileText;
   private String zipname;
}

   
    
    
  










Related examples in the same category

1.Extract contents of a zip file
2.List the contents of a zip file
3.Read entries in a zip / compressed file
4.Decompress a zip file using ZipInputStream
5.Decompress a zip file using ZipFile
6.Create checksum for a zip file
7.Read a zip file checksum value
8.Create a zip file with java.util.zip package
9.Extract file/files from a zip file
10.Read files within a zip file
11.Retrieve a compressed file from a ZIP file
12.Retrieve the contents of a ZIP file
13.Making a zip file of directory including its subdirectories recursively
14.Displaying contents of a compressed zip file
15.Compress a Byte Array
16.Decompress a Byte Array
17.Read zip file
18.Write Zip file
19.The java.util.zip package can be used to create a checksum.
20.Read the content of a zip file ZipFile
21.List the entries of a zip file
22.Compressing Streams: Zipper, Java example
23.Compressing Streams: Parity Checksum
24.Compressing Streams: File Summer
25.Create a simple ZIP File: not retain any directory path information about the files.
26.Decompress a ZIP file.
27.Decompressing a Byte Array
28.Zip unzip byte array
29.Creating a ZIP File
30.Listing the Contents of a ZIP File
31.Retrieving a Compressed File from a ZIP File
32.Calculating the Checksum of a Byte Array (Compute Adler-32 checksum)
33.Compute CRC-32 checksum
34.Calculating the Checksum of a File
35.Compress string(byte array) by Deflater
36.Use Java code to zip a folder
37.Uses Zip compression to compress any number of files given on the command line
38.Load zip file and scan zip file
39.Reading the Contents of a ZIP File
40.UnZip -- print or unzip a JAR or PKZIP file using java.util.zip
41.Tape Archive Lister: Tar file
42.Compressing a Byte Array
43.Tar file stream
44.Tar file and untar file
45.bzip source code
46.Unpack an archive from a URL
47.Compare two zip files
48.Determine whether a file is a ZIP File.
49.Zip up a directory
50.Check sum for a path
51.Check sum for an InputStream
52.Extract zip file to destination folder
53.Return the first directory of this archive. This is needed to determine the plugin directory
54.Makes a zip file named xmlFileName from xmlURL at path
55.Unzipps a zip file placed at zipURL to path
56.A single checksum calculation for multiple files
57.Put file To Zip File
58.Provides both writing and reading from a file which is transparently compressed in Zip
59.TarInputStream reads a UNIX tar archive as an InputStream
60.TarOutputStream writes a UNIX tar archive as an OutputStream
61.Package files utility
62.Zip Compare
63.Unpack a segment from a zip
64.Unpack a zip file
65.Unzip file to a directory
66.Zip a list of file into one zip file.
67.Validate that an archive contains a named entry
68.Compress object and decompress
69.Util for extracting *.jar, *.war and *.zip archives.