Reputation: 41
The problem is we try to use JarFile class to determine whether a file is Jar file or not.
However, if we do it this way, a docx file will also be considered as a Jar file.
Because the docx file is actually a zip file.
Here is my code:
public static boolean detectJarFile(String file) throws IOException {
try {
JarFile jarFile = new JarFile(file);
} catch (java.util.zip.ZipException e) {
// the uploaded file is NOT JAR file
return false;
}
return true;
}
How can I know whether a file is really a Jar file or not?
Any idea?
Upvotes: 4
Views: 5946
Reputation: 128799
// the uploaded file is NOT JAR file
Yes, it is. The problem here is that you assume certain things about a JAR that aren't true. Contrary to some of the other answers here, the only requirement for a JAR file is that it's in the ZIP format. The META-INF/MANIFEST.MF file is optional. A jar isn't required to have .class files in it. It's not required to be anything but a ZIP file. You should reformulate your question to specify exactly what it is you're looking for because it's not a JAR. I suspect that you want to verify that something's not there instead.
Upvotes: 3
Reputation: 74750
In general, a Jar file is nothing else than a zip file with some special properties (which a "normal" zip file might have, but not have to have).
From the JAR File Specification:
JAR file is a file format based on the popular ZIP file format and is used for aggregating many files into one. A JAR file is essentially a zip file that contains an optional META-INF directory.
So, have a look if your candidate has such a directory. If it has (and there is at least a MANIFEST.MF
with the right format in it), it is a jar file.
But being a jar file is nothing special, this knowledge does not really give you anything. It does not have to mean that there are classes in there which you can execute.
As an example, the OpenOffice.org file format (at least the old one, I'm not sure about OpenDocument) is based on the jar format.
Upvotes: 3
Reputation: 32878
In addition to the answer provided by Kal, check whether the file contains at least one file with the extension '.class'. A jar file won't work otherwise, and almost all '.docx' files will not have such a file.
Upvotes: 2
Reputation: 24910
You could check if the file contains a MANIFEST.MF entry.
public static boolean detectJarFile(String file) throws IOException {
...
// First check if this is a zip file.
// Then do this.
ZipFile zip = new ZipFile(file);
boolean hasManifestEntry = zip.getEntry("META-INF/MANIFEST.MF") != null;
zip.close();
return hasManifestEntry;
}
Upvotes: 2