java中实现zip的压缩与解压缩。java自带的 能实现的功能比较有限。
本程序功能:实现简单的压缩和解压缩,压缩文件夹下的所有文件(文件过滤的话需要对File进一步细节处理)。
对中文的支持需要使用java7或java8,可以在ZipOutputStream和ZipInputStream中指定Charset参数,详见API中的构造参数。
1.压缩文件或文件夹
public void zip() throws IOException {
File fileSrc = new File("E:\\abc");
File destFile = new File("E:\\abc.zip");
zip(fileSrc,destFile);
}
public void zip(File fileSrc,File dectFile) throws IOException {
ZipOutputStream zipOutputStream = new ZipOutputStream(new CheckedOutputStream(new FileOutputStream(dectFile),new CRC32()));
String name = fileSrc.getName();
zip(zipOutputStream, name,fileSrc);
zipOutputStream.flush();
zipOutputStream.close();
}
zip
private void zip(ZipOutputStream zipOutputStream,String name, File fileSrc) throws IOException {
if (fileSrc.isDirectory()) {
File[] files = fileSrc.listFiles(new FilenameFilter() { //过滤文件
Pattern pattern = Pattern.compile(".+");//所有文件,正则表达式
@Override
public boolean accept(File dir, String name) {
return pattern.matcher(name).matches();
}
});
zipOutputStream.putNextEntry(new ZipEntry(name+"/")); // 建一个文件夹
name = name+"/";
for (File f : files) {
zip(zipOutputStream,name+f.getName(),f);
}
}else { zipOutputStream.putNextEntry(new ZipEntry(name));
FileInputStream input = new FileInputStream(fileSrc);
byte[] buf = new byte[1024];
int len = -1;
while ((len = input.read(buf)) != -1) {
zipOutputStream.write(buf, 0, len);
}
zipOutputStream.flush();
input.close();
}
}
zip
2.解压缩zip文件
public void unzip() throws IOException {
File zipFile = new File("E:\\java.zip");
String destDir = "E:\\java\\";
unzip(zipFile,destDir);
}
private void unzip(File zipFile, String destDir) throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(new CheckedInputStream(new FileInputStream(zipFile),new CRC32()));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
System.out.println(zipEntry.getName());
File f = new File(destDir + zipEntry.getName());
if(zipEntry.getName().endsWith("/")){
f.mkdirs();
}else {
// f.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(f);
byte[] buf = new byte[1024];
int len = -1;
while ((len = zipInputStream.read(buf)) != -1) { // 直到读到该条目的结尾
fileOutputStream.write(buf, 0, len);
}
fileOutputStream.flush();
fileOutputStream.close();
}
zipInputStream.closeEntry(); //关闭该条目
}
zipInputStream.close();
}
unzip