使用ant包对文件进行解压缩,主要是为了避免中文文件名乱码。
需要先把ant.jar引入工程。
import java.io.*;
import org.apache.tools.zip.*;
public class AntZip {
public static void main(String[] args) {
try {
AntZip.zip("d:\\复件 html-xml", "d:\\复件 html-xml.zip");
AntZip.unzip("d:\\项目资料.zip", "d:\\test");
System.out.println("success");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 压缩zip文件
*/
public static void zip(String filePath, String zipFile)
throws IOException, FileNotFoundException {
File file = new File(filePath);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
compressFiles(file, zos);
zos.close();
}
/**
* 递归压缩文件
*/
private static void compressFiles(File file, ZipOutputStream zos)
throws IOException, FileNotFoundException {
if (file.isDirectory()) {
File[] innerFile = file.listFiles();
if (innerFile != null) {
for (int i = 0; i < innerFile.length; i++) {
compressFiles(innerFile[i], zos);
}
}
} else {
byte[] buf = new byte[2048];
int len;
ZipEntry zipEntry = new ZipEntry(file.getName());
FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fin);
zos.putNextEntry(zipEntry);
while ((len = in.read(buf)) >= 0) {
zos.write(buf, 0, len);
}
in.close();
zos.closeEntry();
}
}
/**
* 解压缩zip文件
*/
public static void unzip(String zipFileName, String outputDirectory) {
try {
ZipFile zipFile = new ZipFile(zipFileName);
java.util.Enumeration e = zipFile.getEntries();
ZipEntry zipEntry = null;
while (e.hasMoreElements()) {
zipEntry = (ZipEntry) e.nextElement();
if (zipEntry.isDirectory()) {
String name = zipEntry.getName();
name = name.substring(0, name.length() - 1);
mkDirs(outputDirectory + File.separator + name);
} else {
String name = zipEntry.getName();
String dir = name.substring(0, name.lastIndexOf("/"));
mkDirs(outputDirectory + File.separator + dir);
File f = new File(outputDirectory + File.separator
+ zipEntry.getName());
f.createNewFile();
InputStream in = zipFile.getInputStream(zipEntry);
FileOutputStream out = new FileOutputStream(f);
int c;
byte[] by = new byte[1024];
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
out.close();
in.close();
}
}
} catch (Exception ex) {
System.out.println("解压文件异常" + ex.getMessage());
ex.printStackTrace();
}
}
/**
* 创建目录,包括子目录
*/
private static void mkDirs(String dir) throws Exception {
if (dir == null || dir.equals(""))
return;
File f1 = new File(dir);
if (!f1.exists())
f1.mkdirs();
}
}