如何在java中识别zip文件? [英] How to identify a zip file in java?

查看:406
本文介绍了如何在java中识别zip文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to identify my archive whether it is zip or rar. But the problem I get runtime error before I can validate my file. I want to create custom notification:

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");
    }
  }
}

目前我有运行时间错误:

At the moment I have runtime error:


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

java.util.zip.ZipException: error in opening zip file


推荐答案

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

I'd suggest to open a plain InputStream an reading the first few bytes (magic bytes) and not to rely on the file extension as this can be easily spoofed. Also, you can omit the overhead creating and parsing the files.

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

For RAR the first bytes should be 52 61 72 21 1A 07.

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

For ZIP it should be one of:


  • 50 4B 03 04

  • 50 4B 05 06 (空档案)

  • 50 4B 07 08 (跨越档案)。

  • 50 4B 03 04
  • 50 4B 05 06 (empty archive)
  • 50 4B 07 08 (spanned archive).

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

另一点,只看你的代码:

Another point, just looked at your code:

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

Why do you catch die InvalidZipException, throw it away and construct a new one? This way you lose all the information from the original exception, making it hard to debug and understand what exactly went wrong. Either don't catch it at all or, if you have to wrap it, do it right:

} catch (InvalidZipException e) {
  throw new InvalidZipException("Not a zip file", e);
}

这篇关于如何在java中识别zip文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆