sun提供的zip缺少对中文的支持,借助ant.jar实现对中文的处理!
package ant;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
/**
* @file_name ZipAndUnzip
* @description 使用ant.jar实现压缩解压缩
* @author 张明亮
* @date 2009.8.30
*/
public class ZipAndUnzip {
/**
* @param zipFileName 指定压缩文件
* @param destDir 指定解压目录
* @throws Exception
*/
public static void unzip(String zipFileName, String destDir)
throws Exception {
try {
ZipFile zipFile = new ZipFile(zipFileName);
Enumeration<?> e = zipFile.getEntries();
ZipEntry zipEntry = null;
File fD = new File(destDir);
if(!fD.exists()){
fD.mkdir();
}
while (e.hasMoreElements()) {
zipEntry = (ZipEntry) e.nextElement();
String entryName = zipEntry.getName();
String names[] = entryName.split("/");
int length = names.length;
String path = destDir;
for (int v = 0; v < length; v++) {
if (v < length - 1) {
path += "/" + names[v];
new File(path).mkdir();
} else {
if (entryName.endsWith("/")) {
new File(destDir + "/" + entryName).mkdir();
} else {
InputStream in = zipFile.getInputStream(zipEntry);
OutputStream os = new FileOutputStream(new File(
destDir + "/" + entryName));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
os.write(buf, 0, len);
}
in.close();
os.close();
}
}
}
}
zipFile.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// try {
// Project prj1 = new Project();
// Expand expand = new Expand();
// expand.setProject(prj1);
// expand.setSrc(new File("d:/tempsrc.zip"));
// expand.setOverwrite(false);
//
// File f = new File("d:/resultZip");
// expand.setDest(f);
// expand.execute();
// } catch (Exception e) {
// e.printStackTrace();
// }
}
/**
* @param targetZip 目标ZIP
* @param sourceFile 源文件
*/
public static void zip(String targetZip, String sourceFile){
Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(new File(targetZip));
FileSet fileSet = new FileSet();
fileSet.setProject(prj);
fileSet.setDir(new File(sourceFile));
// fileSet.setIncludes("**/*.txt");
zip.addFileset(fileSet);
zip.execute();
}
public static void main(String[] args) {
// ============
try {
zip("d:/tempsrc.zip", "d:/ziptest");
unzip("d:/tempsrc.zip", "d:/resultZip");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
藏家569 2025-03-28
藏家838 2025-03-29
奇美拉 2025-03-29
许老头 2025-03-28
藏家942 2025-03-28
mei 2025-03-28
藏家113 2025-03-28
藏家518 2025-03-28
藏家372 2025-03-28
藏家372 2025-03-28