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

查看:50
本文介绍了如何在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");
    }
  }
}

目前我有运行时错误:

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天全站免登陆