如何从Zip文件中读取注释?

时间:2012-03-29 04:01:37

标签: java zipfile

如何使用Java在Zip文件中读写注释?

我可以用这个写评论:

FileOutputStream fos = new FileOutputStream(output);
ZipOutputStream zos = new ZipOutputStream(fos);
zos.setComment("BMC Comment");

2 个答案:

答案 0 :(得分:5)

尝试:

java.util.zip.ZipFile.getComment()

答案 1 :(得分:4)

查看这篇文章:

修改:遗憾的是原始链接现在不可用,这是一个网络存档链接:

http://web.archive.org/web/20100117212418/http://www.flattermann.net:80/2009/01/read-a-zip-file-comment-with-java/

对于后人,这是要点(稍微格式化):

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 + 21] * 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;
}