Program to demonstrate how to read Zip or Jar Archive using Java.
Output of the program :
Video tutorial to demonstrate how to create a Zip File in Java
package com.hubberspot.examples; import java.io.File; import java.io.IOException; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; public class ZipJarReaderDemo { public static void main(String[] args) { // 1. Working with zip files ...... // Create a File and pass a .zip file to it File file = new File("c:\\temp.zip"); try { // Create a ZipFile object by passing File object // to its constructor. ZipFile Opens a ZIP file // for reading File passed. ZipFile zipFile = new ZipFile(file); // ZipFile has a method called as entries() // which returns an enumeration of the ZIP // file entries. Enumeration entries = zipFile.entries(); // looping each file entries by using Enumeration // hasMoreElements() to tests if this enumeration // contains more elements. while(entries.hasMoreElements()) { // ZipEntry class represents a zip entry file in a zip // it is been taken by using nextElement() of Enumeration ZipEntry entry = (ZipEntry) entries.nextElement(); // ZipEntry's getName() returns us the name of file in zip System.out.println("Zip :> File Name : " + entry.getName()); // Tests whether given file is a Directory or not if(entry.isDirectory()) { System.out.println(entry.getName() + " is a Directory"); } else { System.out.println(entry.getName() + " is a File "); } } // closing the zip file zipFile.close(); } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(); // 2. Working with jar files ...... try { // Create a File and pass a .jar file to it file = new File("c:\\temp.jar"); // Create a JarFile object by passing File object // to its constructor. JarFile Opens a JAR file // for reading File passed. JarFile jarFile = new JarFile(file); // JarFile has a method called as entries() // which returns an enumeration of the JAR // file entries. Enumeration entries = jarFile.entries(); // looping each file entries by using Enumeration // hasMoreElements() to tests if this enumeration // contains more elements. while(entries.hasMoreElements()) { // JarEntry class represents a jar entry file in a jar // it is been taken by using nextElement() of Enumeration JarEntry entry = (JarEntry) entries.nextElement(); // JarEntry's getName() returns us the name of file in jar System.out.println("Jar :> File Name : " + entry.getName()); // Tests whether given file is a Directory or not if(entry.isDirectory()) { System.out.println(entry.getName() + " is a Directory"); } else { System.out.println(entry.getName() + " is a File "); } } // closing the jar file jarFile.close(); } catch(IOException io) { io.printStackTrace(); } } }
Output of the program :
Video tutorial to demonstrate how to create a Zip File in Java