事例用的是org.apache.tools.zip包下面的一些类,jdk自带的zip工具类当文件名是中文的情况下会出现问题,本事例可以递归压缩文件和解压文件,功能上和现在常用的一些压缩软件功能类似,暂时没有做性能上的对比。
package zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
@SuppressWarnings("rawtypes")
public class TestAntZip {
public static void main(String[] args) {
//Unzip();
//ZipFile();
}
/**
* 压缩文件或者文件夹
*/
private static void ZipFile() {
try {
String inputStr = "D:/testzip";
File input = new File(inputStr);
String singleFile = null;
if (input.isFile()) {
int temp = input.getName().lastIndexOf(".");
singleFile = input.getName().substring(0, temp);
}
String basepath = input.getName();
String zipfilename = singlefile != null ? singlefile : input.getName();
ZipOutputStream zos = new ZipOutputStream(new File(input.getParent(), zipfilename + ".zip"));
zos.setEncoding("UTF-8");
PutEntry(zos, input, basepath);
zos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void PutEntry(ZipOutputStream zos, File file, String basepath) throws IOException, FileNotFoundException {
FileInputStream is = null;
byte[] b = new byte[1024 * 10];
int tmp = 0;
basepath += File.separator;
if (file.isFile()) {
zos.putNextEntry(new ZipEntry(basepath));
is = new FileInputStream(file);
while ((tmp = is.read(b, 0, b.length)) != -1) {
zos.write(b, 0, tmp);
}
is.close();
} else {
for (File f : file.listFiles()) {
PutEntry(zos, f, basepath + f.getName());
}
}
zos.flush();
}
/**
* 解压缩
*/
private static void Unzip() {
String file = "d:/testzip.zip";
File zipFile = new File(file);
int i = file.lastIndexOf(".");
File filePath = new File(file.substring(0, i));
if (!filePath.exists()) {
filePath.mkdirs();
}
File temp = null;
try {
ZipFile zip = new ZipFile(zipFile, "UTF-8");
ZipEntry entry = null;
byte[] b = new byte[1024 * 10];
int tmp = 0;
FileOutputStream os = null;
InputStream is = null;
for (Enumeration enu = zip.getEntries(); enu.hasMoreElements();) {
entry = (ZipEntry) enu.nextElement();
is = zip.getInputStream(entry);
temp = new File(filePath.getParent() + File.separator + entry.getName());
if (!temp.getParentFile().exists()) {
temp.getParentFile().mkdirs();
}
os = new FileOutputStream(temp);
while ((tmp = is.read(b, 0, b.length)) != -1) {
os.write(b, 0, tmp);
}
os.flush();
os.close();
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}