skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Saturday, September 15, 2012

Zipping and UnZipping Files In Java

Posted by Admin at 4:22 AM – 0 comments
 
Java provides extensive support for zip archives (archived sequences of stored files, which are known as zip entries) via the types located in the java.util.zip package.

represents the source code to a ZipCreate application using ZipOutputStream and ZipEntry to create a zip file and store assorted files in the archive.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipCreate
{
 public static void main(String[] args) throws IOException
 {
  if (args.length < 2)
  {
   System.err.println("usage: java ZipCreate zipfile infile1 "+
     "infile2 ...");
   return;
  }
  try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(args[0])))
  {
   byte[] buf = new byte[1024];
   for (String filename: args)
   {
    if (filename.equals(args[0]))
     continue;
    try (FileInputStream fis = new FileInputStream(filename))
    {
     zos.putNextEntry(new ZipEntry(filename));
     int len;
     while ((len = fis.read(buf)) > 0)
      zos.write(buf, 0, len);
     zos.closeEntry();
    }
   }
  }
 }
}


 represents the source code hot to use ZipInputStream and ZipEntry to access a zip file and extract its entries.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipAccess
{
 public static void main(String[] args) throws IOException
 {
  if (args.length != 1)
  {
   System.err.println("usage: java ZipAccess zipfile");
   return;
  }
  try (ZipInputStream zis =
    new ZipInputStream(new FileInputStream(args[0])))
    {
   byte[] buffer = new byte[4096];
   ZipEntry ze;
   while ((ze = zis.getNextEntry()) != null)
   {
    System.out.println("Extracting: "+ze);
    try (FileOutputStream fos = new FileOutputStream(ze.getName()))
    {
     int numBytes;
     while ((numBytes = zis.read(buffer, 0, buffer.length)) != -1)
      fos.write(buffer, 0, numBytes);
    }
    zis.closeEntry();
   }
    }
 }
}

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger