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?
Asked
Active
Viewed 3,777 times
2 Answers
10
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.

fge
- 119,121
- 33
- 254
- 329
-
1Thanks for your answer , but currently i am working in JDK 1.6 so that it is not possible for me to check. I tried using ZipInputStream but i am not getting any exception – Jojo John Jun 18 '13 at 00:49
-
Well then try the first solution – fge Jun 18 '13 at 05:12
-
Also i tried the code File f = new File("/Users/jojo_john/Downloads/123"); System.out.println("Type:"+new MimetypesFileTypeMap().getContentType(f)); But the even if 123 is a zip file I am getting the output like Type:application/octet-stream – Jojo John Jun 18 '13 at 19:46
-
1Actually the result of calling `probeContentType()` is not always `application/zip`, sometimes it can be `application/x-zip-compressed`. – cнŝdk Jan 03 '19 at 11:05
-
Also there's another problem with this solution. I used it on ZIP file with non-obious extension and it return null. (Linux, openjdk-15) So far checking file signature looks best for me. Just like here https://stackoverflow.com/q/33934178 – Gabriel's Messanger Mar 03 '21 at 20:56
4
Open it using ZipInputStream and check whether it throws ZipException
EDIT: ZipException is the right exception

Jiri Kremser
- 12,471
- 7
- 45
- 72
-
I have tried to open a zip file using ZipInputStream but i am not getting an exception – Jojo John Jun 18 '13 at 00:50
-
-
InputStream theFile; theFile = new FileInputStream("/Users/jojo_john/Downloads/test.pdf"); ZipInputStream stream = new ZipInputStream(theFile); I have tried the above piece of code and its not getting any ZipException. Please check whether the above sample is wrong – Jojo John Jun 18 '13 at 19:42