java.util.zip只支持UTF-8,Ant里面可以指定编码
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class ZipTest
{
/**解压zip*/
private ZipInputStream zipIn;
/**压缩zip*/
private ZipOutputStream zipOut;
private ZipEntry zipEntry;
private static int bufSize;
private byte[] buf;
private int readedBytes;
public ZipTest()
{
this(512);
}
public ZipTest(int bufSize)
{
this.bufSize = bufSize;
this.buf = new byte[this.bufSize];
}
/**
* 压缩文件夹的文件
* @param zipDirectory 需要压缩的文件夹名
*/
public void doZip(String zipDirectory)
{
File file;
File zipDir;
zipDir = new File(zipDirectory);
//压缩后生成的zip文件名
String zipFileName = zipDir.getName() + ".zip";
try
{
this.zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
handleDir(zipDir,this.zipOut);
this.zipOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* 由doZip调用,递归完成目录文件读取
* @param dir
* @param zipOut
* @throws IOException
*/
private void handleDir(File dir,ZipOutputStream zipOut) throws IOException
{
FileInputStream fileIn;
File[] files;
files = dir.listFiles();
if(files.length==0)
{
//如果目录为空,则单独创建
//ZipEntry的isDirectory()方法中,目录是以"/"结尾
this.zipOut.putNextEntry(new ZipEntry(dir.toString()+"/"));
this.zipOut.closeEntry();
}
else
{
//如果目录不为空,则分别处理目录和文件
for(int i=0;i<files.length;i++)
{
File fileName=(File)files[i];
if(fileName.isDirectory())
{
handleDir(fileName,this.zipOut);
}
else
{
fileIn = new FileInputStream(fileName);
this.zipOut.putNextEntry(new ZipEntry(fileName.toString()));
while((this.readedBytes=fileIn.read(this.buf))>0)
{
this.zipOut.write(this.buf , 0 , this.readedBytes);
}
this.zipOut.closeEntry();
}
}
}
}
/**
* 解压指定zip文件
* @param unZipfileName 需要解压的zip文件名
*/
public void unZip(String unZipfileName)
{
FileOutputStream fileOut;
File file;
try
{
this.zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)));
while((this.zipEntry= this.zipIn.getNextEntry())!=null)
{
file = new File(this.zipEntry.getName());
if(this.zipEntry.isDirectory())
{
file.mkdirs();
}
else
{
//如果指定目录不存在,则创建
File parent = file.getParentFile();
if(!parent.exists())
{
parent.mkdirs();
}
fileOut = new FileOutputStream(file);
while((this.readedBytes = this.zipIn.read(this.buf))>0)
{
fileOut.write(this.buf,0,this.readedBytes);
}
fileOut.close();
}
this.zipIn.closeEntry();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void setBufSize(int bufSize)
{
this.bufSize = bufSize;
}
public static void main(String args[]) throws Exception
{
ZipTest ziptest = new ZipTest();
//ziptest.doZip("D:\\tmp");
ziptest.unZip("D:\\workspace\\iipsmssend\\tmp.zip");
}
}