Jojo John
Jojo John

Reputation: 400

Is it possible to find out if a file is a zip file?

I have a file without extension. But I need to find out whether that file is a zip file using java. Is there any way to find out that whether that file is in zip format?

Upvotes: 2

Views: 4512

Answers (2)

fge
fge

Reputation: 121712

There is: try and open a ZipFile on it; if it is not a ZIP, you will get a ZipException.

With JDK 7, it is even easier:

Files.probeContentType(Paths.get("/path/to/file"))

It will return "application/zip" if the file is a zip file!

Bonus: with Java 7, you can access a zip file (or a jar file since a jar is a zip file) as a FileSystem, navigate in it, modify files etc. No more of these pesky ZipEntry/JarEntry objects anymore.

Ditch File. Fast.

Upvotes: 10

Jiri Kremser
Jiri Kremser

Reputation: 12837

Open it using ZipInputStream and check whether it throws ZipException

EDIT: ZipException is the right exception

Upvotes: 4

Related Questions