java 获取zip里附加注释

jdk里面提供了往zip包里添加注释的api方法ZipOutputStream里的setComment,但似乎找不到如何获取zip包里的附加注释的方法,在google里搜了一下,在一个英文网站里发现这个方法,测试可用.


public static String extractZipComment (String filename) {
String retStr = null;
try {
File file = new File(filename);
int fileLen = (int)file.length();

FileInputStream in = new FileInputStream(file);

/* The whole ZIP comment (including the magic byte sequence)
* MUST fit in the buffer
* otherwise, the comment will not be recognized correctly
*
* You can safely increase the buffer size if you like
*/
byte[] buffer = new byte[Math.min(fileLen, 8192)];
int len;

in.skip(fileLen - buffer.length);

if ((len = in.read(buffer)) > 0) {
retStr = getZipCommentFromBuffer (buffer, len);
}

in.close();
} catch (Exception e) {
e.printStackTrace();
}
return retStr;
}

private static String getZipCommentFromBuffer (byte[] buffer, int len) {
byte[] magicDirEnd = {0x50, 0x4b, 0x05, 0x06};
int buffLen = Math.min(buffer.length, len);
//Check the buffer from the end
for (int i = buffLen-magicDirEnd.length-22; i >= 0; i--) {
boolean isMagicStart = true;
for (int k=0; k < magicDirEnd.length; k++) {
if (buffer[i+k] != magicDirEnd[k]) {
isMagicStart = false;
break;
}
}
if (isMagicStart) {
//Magic Start found!
int commentLen = buffer[i+20] + buffer[i+22]*256;
int realLen = buffLen - i - 22;
System.out.println ("ZIP comment found at buffer position " + (i+22) + " with len="+commentLen+", good!");
if (commentLen != realLen) {
System.out.println ("WARNING! ZIP comment size mismatch: directory says len is "+
commentLen+", but file ends after " + realLen + " bytes!");
}
String comment = new String (buffer, i+22, Math.min(commentLen, realLen));
return comment;
}
}
System.out.println ("ERROR! ZIP comment NOT found!");
return null;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值