Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Zipping files with Java.

zip

  • Please log in to reply
No replies to this topic

#1 farrell2k

farrell2k

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 169 posts

Posted 25 November 2013 - 04:01 AM

Today I am going to show you guys how to zip one of more files with Java.  We'll use a simple Swing gui and do the compression in a background thread with a SwingWorker so that we do not freeze our interface, although the utility we create that does the compressions is ui independent, so it can be used with a command line or gui interface.   As with most of my tutorials, I explain it line by line in code, but the best way to learn is to type it in and run it yourself!

 

First up we have the ZipUtils class.  The clas contain the method zip which does all of the compression work.   We utilize InputStreams, OutputStreams, and required classes from the java.util.zip package.

public class ZipUtil {

	// This method accepts any number of files (ZipEntry) and adds them to a zip
	// file specified by name.
	public void zip(String fileName, File[] files) {
		// The name of our zip file.
		File zipFile = new File(fileName);

		// The names of our zip entries. Zip entries are the files to be added
		// to the zip file.
		ZipEntry[] entries = new ZipEntry[files.length];

		// Create an entry from each file and add it to the entries array.
		for (int i = 0; i < files.length; i++) {
			entries[i] = new ZipEntry(files[i].toString());
		}

		// We use a FileInputStream to read data from each individual file
		// (ZipEntry).
		FileInputStream fis = null;

		// We use a FileOutputStream to write each file to disk. This is used by
		// Our ZipOutputStream below.
		FileOutputStream fos = null;

		// We use a ZipOutputStream to write the data from the FileInputStream.
		ZipOutputStream zos = null;

		// This represents the current ZipEntry (file) wer are writing to our
		// zip file.
		ZipEntry entry = null;

		// Create our objects and start the process of reading and writing data.
		try {
			// Create the Outputstream that will write our zip file to disk.
			fos = new FileOutputStream(zipFile);

			// Create out ZipOutputStream that will write to the zip file.
			zos = new ZipOutputStream(fos);

			for (ZipEntry e : entries) {
				// Tell the ZipOutputStream which entry we are working with.
				zos.putNextEntry(e);

				// We need to create a FileInputStream for every ZipEntry (file)
				// so we can read its data.
				fis = new FileInputStream(new File(e.getName()));

				// represents a byte from out file (ZipEntry).
				int data;

				/*
				 * Here is where we cycle through every byte of each ZipEntry
				 * (file) and use the ZipOutputstream to write it. We have
				 * reached EOF when we hit -1. The statement in the while loop
				 * may be confusing, so what it means is the int data =
				 * fis.read(). fis.read() will return one byte from our file,
				 * and as long as that byte is != -1, out while loop should keep
				 * going...
				 */
				while ((data = fis.read()) != -1) {
					// write every byte of data to the ZipOutputStream.
					zos.write(data);
				}

				// We have finished with this ZipEntry, so we close() is to
				// prepare for the next.
				zos.closeEntry();
			}// end for loop.

			// Close all of our streams.
			zos.close();
			fis.close();
			fos.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}// end zip()
}

Next is the Swing interface.   I assume you know how to create a JFrame, so I don't explain that.

public class Main {

	ZipUtil zipper = new ZipUtil();
	
	private JFrame frame;
	
	private JLabel instructionsLabel;
	
	private JButton compressButton;
	
	public Main() {
		buildUI();
	}
	
	private void buildUI() {
		instructionsLabel = new JLabel("  Press the button to add files to the archive.  ");
		
		compressButton = new JButton("Zip");
		compressButton.addActionListener(compressButtonListener);
		
		frame = new JFrame("Zip Utility");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.add(instructionsLabel, BorderLayout.NORTH);
		frame.add(new JPanel() {
			{
				add(compressButton);
			}
		}, BorderLayout.SOUTH);
		frame.pack();frame.setVisible(true);
		frame.setLocationRelativeTo(null);
	}
	
	private ActionListener compressButtonListener = new ActionListener() {
		public void actionPerformed(ActionEvent e) {
			//The file chooser.
			JFileChooser fileChooser = new JFileChooser();
			
			//allow multiple files to be selected.
			fileChooser.setMultiSelectionEnabled(true);
			
			//the result (open or cancel) pressed. 
			int result = fileChooser.showOpenDialog(null);
			
			if (result == JFileChooser.APPROVE_OPTION) {
				//make it so you can't click the button again until the operation is complete.
				compressButton.setEnabled(false);

				//the list of files to compress.
				final File[] filesToCompress = fileChooser.getSelectedFiles();
				
				/* Execute our SwingWorker which will compress out zip files in a background thread, then let us
				 * know when it is finished.  To make things simple, we will create a local inner subclass of 
				 * SwingWorker which for simplicity's sake will not report intermediate progress, although it would be not
				 * too difficult to update progress with a percentage in a JProgressBar.  Our SwingWorker will
				 * return nothing, and will not operate on any specific types, so we use Void, as seen below.  All work is done 
				 * in doInBackgroudnd, and when it is finished done() is called to let us know via a JOptionpane.
				 */
				SwingWorker<Void, Void> zipWorker = new SwingWorker<Void, Void>() {
	
					@Override
					protected Void doInBackground() throws Exception {
						//call the zip method and begin the process.
						zipper.zip("myfile.zip", filesToCompress);
						return null;
					}
					
					@Override
					protected void done() {
						compressButton.setEnabled(true);
						JOptionPane.showMessageDialog(null, "Operation complete.  myfile.zip compressed." +
							" added " + filesToCompress.length + " file(s)");
					}
				};
				
				zipWorker.execute();
			}
		}//end actionPerformed()
	};
	
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new Main();
			}
		});
	}

}
 

Next time I'll show you how to decompress zip files.


Edited by farrell2k, 26 November 2013 - 10:06 AM.

  • 0

Averageloser.com - I used to be a programmer like you, then I took a -> in the knee. 






Also tagged with one or more of these keywords: zip

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download