entryList = zipDecrypter.getEntryList();
for(ExtZipEntry entry : entryList) {
String eName = entry.getName();
String dir = eName.substring(0, eName.lastIndexOf(File.separator) + 1);
File extractDir = new File(outDir, dir);
if (!extractDir.exists()) {
FileUtils.forceMkdir(extractDir);
}
/**
* 抽出文件
*/
File extractFile = new File(outDir + File.separator + eName);
zipDecrypter.extractEntry(entry, extractFile, passwd);
}
} catch (IOException e) {
e.printStackTrace();
} catch (DataFormatException e) {
e.printStackTrace();
} finally {
try {
zipDecrypter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
/**
* 压缩测试
* 可以传文件或者目录
*/
// zip("M:\\ZIP\\test\\bb\\a\\t.txt", "M:\\ZIP\\test\\temp1.zip", "zyh");
// zip("M:\\ZIP\\test\\bb", "M:\\ZIP\\test\\temp2.zip", "zyh");
unzip("M:\\ZIP\\test\\temp2.zip", "M:\\ZIP\\test\\temp", "zyh");
}
}
压缩多个文件时,有两个方法(第一种没试):
(1) 预先把多个文件压缩成zip,然后调用enc.addAll(inZipFile, password);方法将多个zip文件加进来。
(2)针对需要压缩的文件循环调用enc.add(inFile, password);,每次都用相同的密码。
修改源码后的项目可到上面提到的博客去下载,或者参照博客自己修改,其实也很容易,毕竟只有几处改动。
另外我的CSDN下载频道也上传了修改后的源码和jar包,也可以去那里下载。
修改记录
需要修改的文件有:
在ExtZipOutputStream里增加一成员变量并添加两个方法:
protected String encoding = "iso-8859-1";
public boolean utf8Flg = false;
public void setEncoding(String encoding) {
this.encoding = encoding;
utf8Flg |= isUTF8(encoding);
}
protected boolean isUTF8(String encoding) {
if (encoding == null) {
// check platform's default encoding
encoding = System.getProperty("file.encoding");
}
return "UTF8".equalsIgnoreCase(encoding)
|| "UTF-8".equalsIgnoreCase(encoding);
}
然后将ExtZipOutputStream的(134行和158行左右)iso-8859-1编码替换成上面设置的编码格式
接着,再将106行左右文件名长度取得代码改成:
writeShort(entry.getName().getBytes(encoding).length); // file name length
这里有个地方需要注意,当文件名是utf8编码格式的时候,需要设置Zip包的通用位标志 (不明白)
第十一个比特为1,代码修改如下:
修改ExtZipEntry类在initEncryptedEntry方法基础上增加一个重载方法:
public void initEncryptedEntry(boolean utf8Flag) {
setCrc(0); // CRC-32 / for encrypted files it's 0 as AES/MAC checks integritiy
this.flag |= 1; // bit0 - encrypted
if (utf8Flag) {
this.flag |=(1 << 11);
}
// flag |= 8; // bit3 - use data descriptor
this.primaryCompressionMethod = 0x63;
byte[] extraBytes = new byte[11];
extraBytes = new byte[11];
// extra data header ID for AES encryption is 0x9901
extraBytes[0] = 0x01;
extraBytes[1] = (byte)0x99;
// data size (currently 7, but subject to possible increase in the
// future)
extraBytes[2] = 0x07; // data size
extraBytes[3] = 0x00; // data size
// Integer version number specific to the zip vendor
extraBytes[4] = 0x02; // version number
extraBytes[5] = 0x00; // version number
// 2-character vendor ID
extraBytes[6] = 0x41; // vendor id
extraBytes[7] = 0x45; // vendor id
// AES encryption strength - 1=128, 2=192, 3=256
extraBytes[8] = 0x03;
// actual compression method - 0x0000==stored (no compression) - 2 bytes
extraBytes[9] = (byte) (getMethod() & 0xff);
extraBytes[10] = (byte) ((getMet