Search code examples
javaeclipsejarzipexception

"java.util.zip.ZipException: error in opening zip file" when trying to create a new JarFile


I'm trying to create a new JarFile using an existing File object but I keep getting a java.util.zip.ZipException: error in opening zip file.

I'm running the code below:

    File x= new File("C:/Users/Priyanka/Documents/hello.java");
    JarFile jarF = new JarFile(x);

when I run the code above I keep getting the error below:

Exception in thread "main" java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(Unknown Source)
at java.util.zip.ZipFile.<init>(Unknown Source)
at java.util.jar.JarFile.<init>(Unknown Source)
at java.util.jar.JarFile.<init>(Unknown Source)
at prioritization.cfg.Test1.main(Test1.java:12)

I have tried this code on different machines and different version of eclipse but I keep getting the same issue.

I'm have tried to research the problem online but most of the solutions are about trying to open an existing .jar file.

Any help would be appreciated.


Solution

  • If you check the JavaDoc for the JarFile type, you'll see that it's only used for reading existing .jar files.

    The JarFile class is used to read the contents of a jar file from any file that can be opened with java.io.RandomAccessFile. - https://docs.oracle.com/javase/9/docs/api/java/util/jar/JarFile.html

    To create a .jar file, you'll need to use a java.util.jar.JarOutputStream.