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: error in opening zip file
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.
For RAR the first bytes should be 52 61 72 21 1A 07.
For ZIP it should be one of:
Source: https://en.wikipedia.org/wiki/List_of_file_signatures
Another point, just looked at your code:
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);
}