如何在java中识别zip文件?

Jac*_*ack 5 java archive identification

我想确定我的档案是否是ziprar.但是在我可以验证我的文件之前,我遇到运行时错误的问题.我想创建自定义通知:

public class ZipValidator {
  public void validate(Path pathToFile) throws IOException {
    try {
      ZipFile zipFile = new ZipFile(pathToFile.toFile());
      String zipname = zipFile.getName();
    } catch (InvalidZipException e) {
      throw new InvalidZipException("Not a zip file");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

目前我有运行时错误:

java.util.zip.ZipException:打开zip文件时出错

fab*_*ica 15

合并 nanda 和 bratkartoffel 的答案。

private static boolean isArchive(File f) {
    int fileSignature = 0;
    try (RandomAccessFile raf = new RandomAccessFile(f, "r")) {
        fileSignature = raf.readInt();
    } catch (IOException e) {
        // handle if you like
    }
    return fileSignature == 0x504B0304 || fileSignature == 0x504B0506 || fileSignature == 0x504B0708;
}
Run Code Online (Sandbox Code Playgroud)


bra*_*fel 13

我建议打开一个简单的InputStream读取前几个字节(魔术字节)而不依赖于文件扩展名,因为这很容易被欺骗.此外,您可以省略创建和解析文件的开销.

对于RAR,第一个字节应为52 61 72 21 1A 07.

对于ZIP,它应该是以下之一:

  • 50 4B 03 04
  • 50 4B 05 06(空档案)
  • 50 4B 07 08(跨越档案).

资料来源:https://en.wikipedia.org/wiki/List_of_file_signatures

还有一点,只看你的代码:

为什么你会死掉InvalidZipException,抛弃它并构造一个新的?这样您就会丢失原始异常中的所有信息,从而难以调试并了解到底出了什么问题.要么根本不抓住它,要么必须包裹它,做正确的:

} catch (InvalidZipException e) {
  throw new InvalidZipException("Not a zip file", e);
}
Run Code Online (Sandbox Code Playgroud)


小智 4

行中抛出异常

ZipFile zipFile = new ZipFile(pathToFile.toFile());
Run Code Online (Sandbox Code Playgroud)

这是因为如果将非 ZipFile 作为ZipFile构造函数的参数给出,则会ZipException抛出异常。因此,在生成新对象之前,您必须检查ZipFile文件路径是否指向正确的ZipFile. 一种解决方案可能是检查文件路径的扩展名,如下所示

 PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.zip");
 boolean extensionCorrect = matcher.matches(path); 
Run Code Online (Sandbox Code Playgroud)