Import Java.io.File;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.util.Enumeration;
Import Org.apache.tools.zip.ZipEntry;
Import Org.apache.tools.zip.ZipFile;
public class Zip2file {
/**
* Create a directory
* @param path
* Directory Absolute path name
*/
static void Createdir (String path) {
File dir = new file (path);
if (dir.exists () = = False)
Dir.mkdir ();
}
/**
* Unzip zip file
* @param Zipfilepath
* Zip file absolute path
* @param unzipdirectory
* Unzip to True
* @throws Exception
*/
@SuppressWarnings ("Rawtypes")
public static void Unzip (string zipfilepath, String unzipdirectory) throws Exception {
File File = new file (Zipfilepath);
ZipFile zipfile = new ZipFile (file);
Create this zip file to unzip the directory
File Unzipfile = new file (unzipdirectory);
if (Unzipfile.exists ())
Unzipfile.delete ();
Unzipfile.mkdir ();
Get the ZIP File entry enumeration object
Enumeration zipenum = Zipfile.getentries ();
Defining an input-output stream object
InputStream input = null;
OutputStream output = null;
Defining objects
ZipEntry entry = null;
Looping through entries
while (Zipenum.hasmoreelements ()) {
Get Current entry
Entry = (zipentry) zipenum.nextelement ();
String entryName = new String (Entry.getname ());
Use/Separate entry names
String names[] = Entryname.split ("\\/");
int length = Names.length;
String path = Unzipfile.getabsolutepath ();
System.out.println (path+ "----");
for (int v = 0; v < length; v++) {
if (v < length-1) {//directory before last directory
Path + = "/" + Names[v] + "/";
Createdir (path);
} else {//Last
if (Entryname.endswith ("/"))//is a directory, the folder is created
Createdir (Unzipfile.getabsolutepath () + "/" +entryname);
else {//for file, output to file
Input = Zipfile.getinputstream (entry);
Output = new FileOutputStream (New File (Unzipfile.getabsolutepath () + "/" + EntryName));
byte[] buffer = new byte[1024 * 8];
int readlen = 0;
while ((Readlen = input.read (buffer, 0, 1024 * 8))! =-1)
Output.write (buffer, 0, Readlen);
Input.close ();
Output.flush ();
Output.close ();
}
}
}
}
}
public static void Main (string[] args) throws Exception {
Unzip ("D:\\1.zip", "d:\\ new");
System.out.println ("over ....... .......");
}
}
Java Extract Files