import java.util.*;
import java.util.zip.*;
import java.io.*;
import java.lang.*;
public class Unzip {
/**
* @param args
*/
byte doc[]=null;
String Filename=null;
String unzipPath=null;
public Unzip(String filename,String unzippath)
{
Filename=filename;
unzipPath=unzippath;
SetUnZipPath(unzipPath);
}
public Unzip(String filename)
{
Filename=filename;
unzipPath=null;
SetUnZipPath(unzipPath);
}
private void SetUnZipPath(String unzippath)
{
if(unzippath.endsWith("//")) //String类的endsWith(char c)用与判断字符串最后一个字符是否与c相同
unzipPath=new String(unzippath);
else
unzipPath=new String(unzippath+"//");
}
public void doUnZip()
{
try {
ZipInputStream zin=new ZipInputStream(new FileInputStream(Filename));
ZipEntry fentry; //用于表示 ZIP 文件条目
while((fentry=zin.getNextEntry())!=null) //ZipInputStream类的geNextEntry()读取下一个 ZIP 文件条目并将流定位到该条目数据的开始处。
{
if(fentry.isDirectory()) //判断文件条目是否目录条目
checkFilePath(unzipPath+fentry.getName());
else
{
String fname=new String(unzipPath+fentry.getName());
FileOutputStream out=new FileOutputStream(fname);
doc=new byte[512];
int n;
while((n=zin.read(doc, 0, 512))!=-1)out.write(doc,0,n);
out.close();
out=null;
doc=null;
}
}//while
zin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void checkFilePath(String dirName)throws IOException
{
File dir=new File(dirName);
if(!dir.exists())
dir.mkdirs();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String zipFile=args[0];
String unzippath=args[1]+"//";
Unzip myZip=new Unzip(zipFile,unzippath);
myZip.doUnZip();
}
}
/*学习心得
1.File类
mkdirs() 创建目录
2.ZipInputStream类
ZipEntry getNextEntry() 读取下一个 ZIP 文件条目并将流定位到该条目数据的开始处。
int read(byte[] b, int off, int len) 从当前 ZIP 条目读入字节数组,b为缓冲区,off为偏移量,len为读入字节的最大数
3.ZipOutputStream类
int write(byte[] b, int off, int len) 向当前 ZIP 条目写入字节数组
4.ZipEntry类
isDirectory()) 判断文件条目是否目录条目
注意:Zip文件条目的读取和写入方式必须以字符数组为缓冲