Jarsigner - IllegalStateException: zip file closed

E:\>e:\j2sdk1.4.2\bin\jarsigner.exe -verify -verbose e:\eclipse\startup.jar
jarsigner: java.lang.IllegalStateException: zip file closed
any idea? unzip can do unpack the .jar file with no problem
the jar utility can manage the file:
E:\>e:\j2sdk1.4.2\bin\jar tf e:\eclipse\startup.jar
META-INF/
META-INF/MANIFEST.MF
org/
org/eclipse/
org/eclipse/core/
org/eclipse/core/launcher/
org/eclipse/core/launcher/Main$1.class
org/eclipse/core/launcher/Main$Identifier.class
org/eclipse/core/launcher/Main$2.class
org/eclipse/core/launcher/Main.class
org/eclipse/core/launcher/package.html

Better late than never...
http://java.sun.com/j2se/1.4.2/relnotes.html#jarsigner

Similar Messages

  • Java Plug-in 1.4.0 throws an IllegalStateException: zip file closed

    Cross-posting to reach a wider audience:
    Java Plug-in 1.4.0 throws an IllegalStateException: zip file closed
    Author: remyb Jul 23, 2002 6:36 AM
    A IllegalStateException is thrown when the class loader
    try to load a class from my applet JAR file.
    The applet is embedded in a JSP page which use the Plug-In 1.4.0.
    That JSP is hosted by Tomcat 4.0.1.
    The applet JAR file is signed with a self-signed certificate.
    The applet has been compiled with JDK 1.4.0.
    The jar has been put in the Plug-in cache successfully.
    Here is the stack trace I got in the Java Console ...
    java.lang.IllegalStateException: zip file closed
    at java.util.zip.ZipFile.getEntry(Unknown Source)
    at java.util.jar.JarFile.getEntry(Unknown Source)
    at sun.plugin.cache.CachedJarFile.getEntry(Unknown Source)
    at java.util.jar.JarFile.getJarEntry(Unknown Source)
    at sun.misc.URLClassPath$JarLoader.getResource(Unknown Source)
    at sun.misc.URLClassPath.getResource(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at sun.applet.AppletClassLoader.findClass(Unknown Source)
    at sun.plugin.security.PluginClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.applet.AppletClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    Please somebody help me !!
    Thanks !
    Re: Java Plug-in 1.4.0 throws an IllegalStateException: zip file closed
    Author: mutmansky
    In Reply To: Java Plug-in 1.4.0 throws an IllegalStateException: zip file closed Jul 26, 2002 6:36 AM
    Reply 1 of 1
    I've got a very similar error, but unfortuneatly I don't have an answer yet. The only difference is that my Applet is embedded in a standard HTML page, and loaded via Apache. Once the Applet runs, it then communicates with the servlet via Tomcat. I also exchange data with another server task via CORBA.
    But everything else is the same, self-signed applet, applet compiles successfully, and jar is being put in the Plug-in Caceh successfully.
    I have narrowed the problem down a bit, and maybe you can tell me if you're in a similar situation:
    In my case, I need to encrypt the data that I'm sending through CORBA, so I create a Cipher object using Cipher.getInstance(). This method call seems to be the catalyst of my troubles. No matter where I move that call in my code, the next time the code tries to instantiate a class defined in my applet jar file after that "getInstance" call, I get the "zip file closed error." It's like the classloader is confused, because the Cipher.getInstance method would be accessing a different jar file or something. Are you trying to do something similar? Maybe not creating a Cipher, but creating some other object defined outside your own jar-file?
    To top it off, if I disable caching in the Plugin control panel, everything works fine. But that's not really an option for me, since it slows things down a lot, and I can't make all my users go into their control panels and disable caching. But at leasts it makes me confident that there's not a problem with my code.
    In my latest attempt to circumvent this problem, I even put the Cipher.getInstance() call in a static initializer. Here's the stack trace from that attempt:
    java.lang.IllegalStateException: zip file closed
    at java.util.zip.ZipFile.getEntry(Unknown Source)
    at java.util.jar.JarFile.getEntry(Unknown Source)
    at sun.plugin.cache.CachedJarFile.getEntry(Unknown Source)
    at java.util.jar.JarFile.getJarEntry(Unknown Source)
    at sun.misc.URLClassPath$JarLoader.getResource(Unknown Source)
    at sun.misc.URLClassPath.getResource(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at sun.applet.AppletClassLoader.findClass(Unknown Source)
    at sun.plugin.security.PluginClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.applet.AppletClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    at com.uss.wbi.client.WBIClient.<init>(WBIClient.java:404)
    at com.uss.wbi.client.WBIApplet.init(WBIApplet.java:122)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    In other words, since the getInstance method is in a static initializer, the next thing to run is the applet.init(), which is what is failing now. If I move the Cipher.getInstance method into the client constructor, the next time I instantiate a new object, I'll get the error there.
    Has anybody else seen anything like this? Or does anybody know how I can flush the Cache from the applet code? Or can I reset the ClassLoader in some way in the code?
    Thanks,
    Steve

    Well, I finally came to a solution that is acceptable at least to me, if not ideal. I've started using the BouncyCastle lightweight API. This makes my code somewhat more complicated, and I had to bundle up all the BouncyCastle classes that I'm using into a jar file, and download that to my applet along with my client jar file (after signing the jar files). Using this Lightweight API bypasses the Cipher.getInstance() method all together, and is a little harder to use, but at least everything is working consistently now.
    I still believe this to be a bug either in the ClassLoader or the Cipher.getInstance() method. I intend to try to write a test applet that reproduces the error in a more simple way and if I can pull that off, I'll submit a bug report to Sun.
    Thanks to all who responded!!
    Steve

  • JSP compilation failed with java.lang.IllegalStateException: zip file close

    Hi,
    I have a web app successfully deployed on Weblogic7.0 and HP UX 11.0, which uses jdk 1.3.1_02
    In this application, when i invoke a jsp (this exception occurs on any jsp not to any specific jsp), i found the following exception trace on wl-domain.log file and server crashes: -
    java.lang.IllegalStateException: zip file closed
         at java.util.zip.ZipFile.getEntry(Unknown Source)
         at weblogic.servlet.internal.WarClassFinder.getSource(WarClassFinder.java, Compiled Code)
         at weblogic.servlet.internal.WarClassFinder.getSource(WarClassFinder.java, Compiled Code)
         at weblogic.utils.classloaders.MultiClassFinder.getSource(MultiClassFinder.java, Compiled Code)
         at weblogic.utils.classloaders.MultiClassFinder.getSource(MultiClassFinder.java, Compiled Code)
         at weblogic.utils.classloaders.MultiClassFinder.getClassSource(MultiClassFinder.java, Compiled Code)
         at weblogic.utils.classloaders.ChangeAwareClassLoader.upToDate(ChangeAwareClassLoader.java, Compiled Code)
         at weblogic.servlet.internal.ServletStubImpl.createServlet(ServletStubImpl.java, Compiled Code)
         at weblogic.servlet.internal.ServletStubImpl.checkForReload(ServletStubImpl.java, Compiled Code)
         at weblogic.servlet.internal.ServletStubImpl.getServlet(ServletStubImpl.java, Compiled Code)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java, Compiled Code)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java, Compiled Code)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java, Compiled Code)
         at weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManager.java, Compiled Code)
         at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java, Compiled Code)
         at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java, Compiled Code)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java, Compiled Code)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java, Compiled Code)
    Can anyone help me in figuring out this problem urgently?
    thanks in advance
    manoj

    Hi Manoj.I am also getting the same problem in the weblogicserver version-6.1 SP2.It is also using the jdk 1.31.
    here is my stack trace.Help i smuch appreciated.!!
    java.lang.IllegalStateException: zip file closed
         at java.util.zip.ZipFile.getEntry(ZipFile.java:141)
         at weblogic.servlet.internal.WarClassFinder.getSource(WarClassFinder.java:197)
         at weblogic.servlet.internal.WarClassFinder.getSource(WarClassFinder.java:106)
         at weblogic.utils.classloaders.MultiClassFinder.getSource(MultiClassFinder.java:53)
         at weblogic.utils.classloaders.MultiClassFinder.getSource(MultiClassFinder.java:53)
         at weblogic.utils.classloaders.MultiClassFinder.getClassSource(MultiClassFinder.java:45)
         at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:265)
         at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:156)
         at weblogic.utils.classloaders.ChangeAwareClassLoader.findClass(ChangeAwareClassLoader.java:65)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:297)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:253)
         at weblogic.utils.classloaders.ChangeAwareClassLoader.loadClass(ChangeAwareClassLoader.java:43)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:313)
         at org.exolab.castor.xml.Unmarshaller.unmarshal(Unknown Source)
         at org.exolab.castor.xml.Unmarshaller.unmarshal(Unknown Source)
         at org.exolab.castor.xml.Unmarshaller.unmarshal(Unknown Source)
         at com.slfc.framework.service.ServiceMessageFactory.createServiceResult(ServiceMessageFactory.java:58)
         at sunlife.nexus.admin.SecPro.establishSupportSession(Unknown Source)
         at sunlife.nexus.admin.Page_secPro_extAppLoader.processPageRequest(Unknown Source)
         at sunlife.wis.servlets.WISServlet.redirect(WISServlet.java:63)
         at sunlife.wis.servlets.WISServlet.doExec(WISServlet.java:107)
         at sunlife.wis.servlets.WISServlet.doGet(WISServlet.java:70)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:265)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:200)
         at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:2495)
         at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2204)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:139)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)

  • Zip File closed

    Hi
    I am trying to use the new Mustang release which has the CMS bug causing long rescans fixed. However, I am running into this exception which occurs in b71 but not Java 1.5.0
    Caused by: java.lang.IllegalStateException: zip file closed
                   at java.util.zip.ZipFile.ensureOpen(ZipFile.java:402)
                   at java.util.zip.ZipFile.getEntry(ZipFile.java:147)
                   at java.util.jar.JarFile.getEntry(JarFile.java:205)
                   at com.foo.cam.net.jar.URLJarFile.getEntry(URLJarFile.java:65)
                   at java.util.jar.JarFile.getJarEntry(JarFile.java:188)
                   at sun.misc.JarIndex.getJarIndex(JarIndex.java:96)
                   at sun.misc.URLClassPath$JarLoader$1.run(URLClassPath.java:606)
                   at java.security.AccessController.doPrivileged(Native Method)
                   at sun.misc.URLClassPath$JarLoader.ensureOpen(URLClassPath.java:597)
                   at sun.misc.URLClassPath$JarLoader.<init>(URLClassPath.java:559)
                   at sun.misc.URLClassPath$3.run(URLClassPath.java:331)
                   at java.security.AccessController.doPrivileged(Native Method)
                   at sun.misc.URLClassPath.getLoader(URLClassPath.java:320)
                   at sun.misc.URLClassPath.getLoader(URLClassPath.java:297)
                   at sun.misc.URLClassPath.access$000(URLClassPath.java:59)
                   at sun.misc.URLClassPath$1.next(URLClassPath.java:194)
                   at sun.misc.URLClassPath$1.hasMoreElements(URLClassPath.java:205)
                   at java.net.URLClassLoader$3$1.run(URLClassLoader.java:393)
                   at java.security.AccessController.doPrivileged(Native Method)
                   at java.net.URLClassLoader$3.next(URLClassLoader.java:390)
                   at java.net.URLClassLoader$3.hasMoreElements(URLClassLoader.java:415)
                   at sun.misc.CompoundEnumeration.next(CompoundEnumeration.java:27)
                   at sun.misc.CompoundEnumeration.hasMoreElements(CompoundEnumeration.java:36)
                   at sun.misc.Service$LazyIterator.hasNext(Service.java:255)
                   at java.sql.DriverManager.loadInitialDrivers(DriverManager.java:476)
                   at java.sql.DriverManager.initialize(DriverManager.java:579)
                   at java.sql.DriverManager.registerDriver(DriverManager.java:270)
                   at com.sybase.jdbc2.jdbc.SybDriver.registerWithDriverManager(SybDriver.java:561)
                   at com.sybase.jdbc2.jdbc.SybDriver.<init>(SybDriver.java:113)
                   at com.sybase.jdbc2.jdbc.SybDriver.<clinit>(SybDriver.java:79)
                   ... 14 moreThis seems that the jar file has been closed prematurely, causing an exception when it is being read. I cannot seem to find any regression bug in the database with this symptom. Any ideas for a solution or workaround for this problem? Any help would be much appreciated.
    Thanks.

    Currently i have the same problem with the bouncy castle JCE security jar :
    No such algorithm: DES
    java.security.NoSuchAlgorithmException: No such algorithm: DES
         at javax.crypto.Cipher.getInstance(DashoA14*..)
         at javax.crypto.Cipher.getInstance(DashoA14*..)
    Caused by: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: DES, provider: BC, class: org.bouncycastle.jce.provider.JCEBlockCipher$DES)
         at java.security.Provider$Service.newInstance(Unknown Source)
         ... 9 more
    Caused by: java.lang.IllegalStateException: zip file closed
         at java.util.zip.ZipFile.ensureOpen(Unknown Source)
         at java.util.zip.ZipFile.getEntry(Unknown Source)
         at java.util.jar.JarFile.getEntry(Unknown Source)
         at com.sun.deploy.cache.CachedJarFile.getEntry(Unknown Source)
         at java.util.jar.JarFile.getJarEntry(Unknown Source)
         at sun.misc.URLClassPath$JarLoader.getResource(Unknown Source)
         at sun.misc.URLClassPath.getResource(Unknown Source)
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(Unknown Source)
         at sun.applet.AppletClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.security.Provider$Service.getImplClass(Unknown Source)
         ... 10 more

  • Excel 2013 (office 365) crashes every time I opened a excel file directly from Browser or zip file.

    Hi guys,
    I got a problem with my Office 365 that every time I open an office file from IE/chrome browser (i.e. click the document link and save the file to local, open it in the browser after download completed) or under a zip file, no matter it is an excel file
    or word document, the Excel/Word crashes. The Excel/Word will ask me to repair the file if I open the file again. The file will be closed automatically after the repair, when I open the file again it will told me the excel/word itself has just successfully
    registered and ask me to close and re-open the excel again in order to enable editing the file. This is extremely inconvenience, I have to open this file 4 times to edit my file. 
    Could anyone here can help me to resolve the problem?
    Many thanks.

    Hi,
    According to your description, Excel seems not crash when you opened a local Excel/Word file directly. Where do you store these file? OneDrive, SharePoint or other?
    If possible, please let me see the screenshot of the error dialog.
    Moreover, please open Event Viewer to check whether there's any error about the Excel/Word crash issue.
    Press Win + R, type "eventvwr" in the blank box, press Enter. In the Event Viewer, browse to Windows Logs -> Application, there may be some errors after the crash.
    To protect your privacy, you may send the error logs to
    [email protected], we will try to find the cause.
    Regards,
    George Zhao
    Forum Support
    Come back and mark the replies as answers if they help and unmark them if they provide no help.
    If you have any feedback on our support, please click "[email protected]"

  • Writing objects with in zip files

    Hi,
    I am trying to write an object into a zip file :
    ZipOutputStream zout=new ZipOutputStream(new FileOutputStream("test.zip");
    ZipEntry ze=new ZipEntry("test.dat");
    zout.putNextEntry(ze);
    ObjectOutputStream out=new ObjectOutputStream(zout);
    out.writeObject(obj);
    out.close();
    zout.closeEntry();
    zout.close();
    The above code is within a try-catch block.
    It is compiling correctly.
    But it is throwing an exception just after executing "zout.closeEntry()".
    The exception is "java.io.Exception: Stream Closed".
    I am using JDK 1.3.
    Can anyone help me.
    Indra.

    Hi Indra,
    I'm sorry it didn't work. I would try to simulate that problem but I really don't have time right now (but I will).
    What you can do is to try to create that zip file in 2 steps, first just serialize the objects in a ordinary file and then read from that file and create a zip file. Of course you'll have to do the same to get your objects out from the zip file.
    If the file is not too big you can use a ByteArrayOutputStream instead of a FileOutputStream for the first file.
    hope it will work,
    Gabe

  • Error in reading the contents of a zip file

    EHello Experts,
    I want to read the contents of a zip file.I have written the following program which reads the contents of a file named "index.xml" which resides in ReadZip.zip.My problem is , it is reading only the first line of that file & after that it is giving this error.
    java.io.IOException: Stream closed
    at java.util.zip.ZipInputStream.ensureOpen(ZipInputStream.java:43)
    at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:67)
    at components.ReadZipFile2.main(ReadZipFile2.java:26)
    public class ReadZipFile2 {
        public static void main(String args[]) {
            try {
                FileInputStream fis = new FileInputStream("C:\\ReadZip.zip");
                ZipInputStream zis = new ZipInputStream(fis);
                ZipEntry ze;
                while ((ze = zis.getNextEntry()) != null) {
                    System.out.println(ze.getName());
                    if (ze.getName().equals("ReadZip/index.xml")) {
                        long size = ze.getSize();
                        if (size > 0) {
                            System.out.println("Length is " + size);
                            BufferedReader br = new BufferedReader(
                                    new InputStreamReader(zis));
                            String line;
                            while ((line = br.readLine()) != null) {
                                System.out.println(line);
                            br.close();
            } catch (IOException e) {
                e.printStackTrace();
    }It seems that zis is getting close after reading the first entry of file.I am unable to guess the reason for this.Please help.Thanx in advance.

    [redacted confused advice]
    [_Compressing and Decompressing Data using Java - with many code samples_|http://java.sun.com/developer/technicalArticles/Programming/compression/|Yes Virginia, there really are code samples]

  • Problem in ZIP file encryption

    Hi Folks,
    I am facing a problem while encrypting and decrypting a ZIP file. The result file is corrupted.
    If i encrypt .txt and .doc files, i am able to get them in decryption. But problem with ZIP files. What could be the reasone?
    I am using AES algorithem.
    Key Generator code is:
    ================
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128); //128 bitskey = kgen.generateKey();
    Encryption:
    ========
    Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    //paramSpec is a Initialization Vector
    ecipher.init(Cipher.ENCRYPT_MODE, skey, paramSpec);
    FileInputStream in = new FileInputStream("c:\\encryption\\Source.zip");
    FileOutputStream out = new FileOutputStream("c:\\cipher\\cipher.enc");
    OutputStream cout = new CipherOutputStream(out, ecipher);
    int numRead = 0;
    while ((numRead = in.read(buf)) >= 0) {     
    cout.write(buf, 0, numRead);
    Decryption:
    ========
    Cipher dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    dcipher.init(Cipher.DECRYPT_MODE, skey, paramSpec);
    FileInputStream fis = new FileInputStream("c:\\cipher\\cipher.enc");
    InputStream in = new CipherInputStream(fis, dcipher);
    FileOutputStream fos = new FileOutputStream("c:\\encryption\\Result.zip");
    int numRead = 0;
    while ((numRead = in.read(buf)) >= 0) {    
    fos.write(buf, 0, numRead);
    }

    bala_1404 wrote:
    i closed them in the program. i just pasted important lines of my program.You have a program that does not work and you don't know why yet you feel confident enough in your diagnosis to show just the lines where you think the problem lies. I'm betting that you are closing the wrong streams but of course I am guessing since I can't see the code that matters.
    Good luck.

  • Cannot extract Zip file with Winzip after zipping with java.util.zip

    Hi all,
    I write a class for zip and unzip the text files together which can be zip and unzip successfully with Java platform. However, I cannot extract the zip file with Winzip or even WinRAR after zipping with Java platform.
    Please help to comment, thanks~
    Below is the code:
    =====================================================================
    package myapp.util;
    import java.io.* ;
    import java.util.TreeMap ;
    import java.util.zip.* ;
    import myapp.exception.UserException ;
    public class CompressionUtil {
      public CompressionUtil() {
        super() ;
      public void createZip(String zipName, String fileName)
          throws ZipException, FileNotFoundException, IOException, UserException {
        FileOutputStream fos = null ;
        BufferedOutputStream bos = null ;
        ZipOutputStream zos = null ;
        File file = null ;
        try {
          file = new File(zipName) ; //new zip file
          if (file.isDirectory()) //check if it is a directory
         throw new UserException("Invalid zip file ["+zipName+"]") ;
          if (file.exists() && !file.canWrite()) //check if it is readonly
         throw new UserException("Zip file is ReadOnly ["+zipName+"]") ;
          if (file.exists()) //overwrite the existing file
         file.delete();
          file.createNewFile();
          //instantiate the ZipOutputStream
          fos = new FileOutputStream(file) ;
          bos = new BufferedOutputStream(fos) ;
          zos = new ZipOutputStream(bos) ;
          this.writeZipFileEntry(zos, fileName); //call to write the file into the zip
          zos.finish() ;
        catch (ZipException ze) {
          throw ze ;
        catch (FileNotFoundException fnfe) {
          throw fnfe ;
        catch (IOException ioe) {
          throw ioe ;
        catch (UserException ue) {
          throw ue ;
        finally {
          //close all the stream and file
          if (fos != null)
         fos.close() ;
          if (bos != null)
         bos.close();
          if (zos != null)
         zos.close();
          if (file != null)
         file = null ;
        }//end of try-catch-finally
      private void writeZipFileEntry(ZipOutputStream zos, String fileName)
          throws ZipException, FileNotFoundException, IOException, UserException {
        BufferedInputStream bis = null ;
        File file = null ;
        ZipEntry zentry = null ;
        byte[] bArray = null ;
        try {
          file = new File(fileName) ; //instantiate the file
          if (!file.exists()) //check if the file is not exist
         throw new UserException("No such file ["+fileName+"]") ;
          if (file.isDirectory()) //check if the file is a directory
         throw new UserException("Invalid file ["+fileName+"]") ;
          //instantiate the BufferedInputStream
          bis = new BufferedInputStream(new FileInputStream(file)) ;
          //Get the content of the file and put into the byte[]
          int size = (int) file.length();
          if (size == -1)
         throw new UserException("Cannot determine the file size [" +fileName + "]");
          bArray = new byte[(int) size];
          int rb = 0;
          int chunk = 0;
          while (((int) size - rb) > 0) {
         chunk = bis.read(bArray, rb, (int) size - rb);
         if (chunk == -1)
           break;
         rb += chunk;
          }//end of while (((int)size - rb) > 0)
          //instantiate the CRC32
          CRC32 crc = new CRC32() ;
          crc.update(bArray, 0, size);
          //instantiate the ZipEntry
          zentry = new ZipEntry(fileName) ;
          zentry.setMethod(ZipEntry.STORED) ;
          zentry.setSize(size);
          zentry.setCrc(crc.getValue());
          //write all the info to the ZipOutputStream
          zos.putNextEntry(zentry);
          zos.write(bArray, 0, size);
          zos.closeEntry();
        catch (ZipException ze) {
          throw ze ;
        catch (FileNotFoundException fnfe) {
          throw fnfe ;
        catch (IOException ioe) {
          throw ioe ;
        catch (UserException ue) {
          throw ue ;
        finally {
          //close all the stream and file
          if (bis != null)
         bis.close();
          if (file != null)
         file = null ;
        }//end of try-catch-finally
    }

    Tried~
    The problem is still here~ >___<
    Anyway, thanks for information sharing~
    The message is:
    Cannot open file: it does not appear to be a valid archive.
    If you downloaded this file, try downloading the file again.
    The problem may be here:
    if (fos != null)
    fos.close() ;
    if (bos != null)
    bos.close();
    if (zos != null)
    zos.close();
    if (file != null)
    file = null ;
    The fos is closed before bos so the last buffer is not
    saved.
    zos.close() is enough.

  • Cannot use winzip to unzip the zip file zipped by java.util.zip

    Hi all,
    I use the followcode to create a zip file, and i downlaod it and try to use winzip to unzip this file but fail. The path is correct and i got the zip file. but it just cannot unzip.
    pls help
    thanks alot.
    Kin
              int count = 0;
              count = ContentDocuments.size();
              for (int i = 0; i < bb; i++)     {
                   System.out.println(filenames[i] + "");
              // Create a buffer for reading the files
              byte[] buf = new byte[10*1024*1024];
              try {      
                   String outFilename = MyDir + "zipfile/" + getContentID2()+".zip";
                   System.out.println("outFilename = " + outFilename);
                   ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
                   for (int i=0; i<filenames.length; i++) {           
                        FileInputStream in = new FileInputStream(filenames);
                        out.putNextEntry(new ZipEntry(filenames[i]));
                        int len;
                        while ((len = in.read(buf)) != -1) {               
                             out.write(buf, 0, len);
                        out.closeEntry();
                        in.close();
                   out.close();
              } catch (IOException e)     {
                   System.err.println("zipprocess " + e.getMessage());

    I've written a replacement zip file creator class. Not much tested but it seems to work, however I've yet to try it with the version of WINZIP that rejected my previous attempts. Oh, and the stored dates are garbage.
    * ZipOutputFile.java
    * Created on 25 March 2004, 13:08
    package zip;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    * <p>Creates a ZIP archive in a file which WINZIP should be able to read.</p>
    * <p>Unfortunately zip archives generated by the standard Java class
    * {@link java.util.zip.ZipOutputStream}, while adhering to PKZIPs format specification,
    * don't appear to be readable by some versions of WinZip and similar utilities. This is
    * probably because they use
    * a format specified for writing to a non-seakable stream, where the length and CRC of
    * a file is writen to a special block following the data. Since the length of the binary
    * date is unknown this makes an archive quite complicated to read, and it looks like
    * WinZip hasn't bothered.</p>
    * <p>All data is Deflated. Close completes the archive, flush terminates the current entry.</p>
    * @see java.util.zip.ZipOutputStream
    * @author  Malcolm McMahon
    public class ZipOutputFile extends java.io.OutputStream {
        byte[] oneByte = new byte[1];
        java.io.RandomAccessFile archive;
        public final static short DEFLATE_METHOD = 8;
        public final static short VERSION_CODE = 20;
        public final static short MIN_VERSION = 10;
        public final static int  ENTRY_HEADER_MAGIC = 0x04034b50;
        public final static int  CATALOG_HEADER_MAGIC = 0x02014b50;
        public final static int  CATALOG_END_MAGIC = 0x06054b50;
        private final static short DISC_NUMBER = 0;
        ByteBuffer entryHeader = ByteBuffer.wrap(new byte[30]);
        ByteBuffer entryLater = ByteBuffer.wrap(new byte[12]);
        java.util.zip.CRC32 crcAcc = new java.util.zip.CRC32();
        java.util.zip.Deflater def = new java.util.zip.Deflater(java.util.zip.Deflater.DEFLATED, true);
        int totalCompressed;
        long MSEPOCH;
        byte [] deflateBuf = new byte[2048];
        public static final long SECONDS_TO_DAYS = 60 * 60 * 24;
         * Entry stores info about each file stored
        private class Entry {
            long offset;        // position of header in file
            byte[] name;
            long crc;
            int compressedSize;
            int uncompressedSize;
            java.util.Date date;
             * Contructor also writes initial header.
             * @param fileName Name under which data is stored.
             * @param date  Date to label the file with
             * @TODO get the date stored properly
            public Entry(String fileName, java.util.Date date) throws IOException {
                name = fileName.getBytes();
                this.date = date == null ? new java.util.Date() : date;
                entryHeader.position(10);
                putDate(entryHeader);
                entryHeader.putShort(26, (short)name.length);
                offset = archive.getFilePointer();
                archive.write(entryHeader.array());
                archive.write(name);
                catalog.add(this);
                crcAcc.reset();
                totalCompressed = 0;
                def.reset();
             * Finish writing entry data. Save the lenghts & crc for catalog
             * and go back and fill them in in the entry header.
            public void close() throws IOException {
                def.finish();
                while(!def.finished())
                    deflate();
                entryLater.position(0);
                crc = crcAcc.getValue();
                compressedSize = totalCompressed;
                uncompressedSize = def.getTotalIn();
                entryLater.putInt((int)crc);
                entryLater.putInt(compressedSize);
                entryLater.putInt(uncompressedSize);
                long eof = archive.getFilePointer();
                archive.seek(offset + 14);
                archive.write(entryLater.array());
                archive.seek(eof);
             * Write the catalog data relevant to this entry. Buffer is
             * preloaded with fixed data.
             * @param buf Buffer to organise fixed lenght part of header
            public void writeCatalog(ByteBuffer buf) throws IOException {
                buf.position(12);
                putDate(buf);
                buf.putInt((int)crc);
                buf.putInt(compressedSize);
                buf.putInt(uncompressedSize);
                buf.putShort((short)name.length);
                buf.putShort((short)0);  // extra field length
                buf.putShort((short)0);  // file comment length
                buf.putShort(DISC_NUMBER);  // disk number
                buf.putShort((short)0); // internal attributes
                buf.putInt(0);      // external file attributes
                buf.putInt((int)offset); // file position
                archive.write(buf.array());
                archive.write(name);
             * This writes the entries date in MSDOS format.
             * @param buf Where to write it
             * @TODO Get this generating sane dates
            public void putDate(ByteBuffer buf) {
                long msTime = (date.getTime() - MSEPOCH) / 1000;
                buf.putShort((short)(msTime % SECONDS_TO_DAYS));
                buf.putShort((short)(msTime / SECONDS_TO_DAYS));
        private Entry entryInProgress = null; // entry currently being written
        private java.util.ArrayList catalog = new java.util.ArrayList(12);  // all entries
         * Start a new output file.
         * @param name The name to store as
         * @param date Date - null indicates current time
        public java.io.OutputStream openEntry(String name, java.util.Date date) throws IOException{
            if(entryInProgress != null)
                entryInProgress.close();
            entryInProgress = new Entry(name, date);
            return this;
         * Creates a new instance of ZipOutputFile
         * @param fd The file to write to
        public ZipOutputFile(java.io.File fd) throws IOException {
            this(new java.io.RandomAccessFile(fd, "rw"));
         * Create new instance of ZipOutputFile from RandomAccessFile
         * @param archive RandomAccessFile
        public ZipOutputFile(java.io.RandomAccessFile archive) {
            this.archive = archive;
            entryHeader.order(java.nio.ByteOrder.LITTLE_ENDIAN);  // create fixed fields of header
            entryLater.order(java.nio.ByteOrder.LITTLE_ENDIAN);
            entryHeader.putInt(ENTRY_HEADER_MAGIC);
            entryHeader.putShort(MIN_VERSION);
            entryHeader.putShort((short)0);  // general purpose flag
            entryHeader.putShort(DEFLATE_METHOD);
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.clear();
            cal.set(java.util.Calendar.YEAR, 1950);
            cal.set(java.util.Calendar.DAY_OF_MONTH, 1);
    //        def.setStrategy(Deflater.HUFFMAN_ONLY);
            MSEPOCH = cal.getTimeInMillis();
         * Writes the master catalogue and postamble and closes the archive file.
        public void close() throws IOException{
            if(entryInProgress != null)
                entryInProgress.close();
            ByteBuffer catEntry = ByteBuffer.wrap(new byte[46]);
            catEntry.order(java.nio.ByteOrder.LITTLE_ENDIAN);
            catEntry.putInt(CATALOG_HEADER_MAGIC);
            catEntry.putShort(VERSION_CODE);
            catEntry.putShort(MIN_VERSION);
            catEntry.putShort((short)0);
            catEntry.putShort(DEFLATE_METHOD);
            long catStart = archive.getFilePointer();
            for(java.util.Iterator it = catalog.iterator(); it.hasNext();) {
                ((Entry)it.next()).writeCatalog(catEntry);
            catEntry.position(0);
            catEntry.putInt(CATALOG_END_MAGIC);
            catEntry.putShort(DISC_NUMBER);
            catEntry.putShort(DISC_NUMBER);
            catEntry.putShort((short)catalog.size());
            catEntry.putShort((short)catalog.size());
            catEntry.putInt((int)(archive.getFilePointer() - catStart));
            catEntry.putInt((int)catStart);
            catEntry.putShort((short)0);
            archive.write(catEntry.array(), 0, catEntry.position());
            archive.setLength(archive.getFilePointer());  // truncate if old file
            archive.close();
            def.end();
         * Closes entry in progress.
        public void flush() throws IOException{
            if(entryInProgress == null)
                throw new IllegalStateException("Must call openEntry before writing");
            entryInProgress.close();
            entryInProgress = null;
         * Standard write routine. Defined by {@link java.io.OutputStream}.
         * Can only be used once openEntry has defined the file.
         * @param b  Bytes to write
        public void write(byte[] b) throws IOException{
            if(entryInProgress == null)
                throw new IllegalStateException("Must call openEntry before writing");
            crcAcc.update(b);
            def.setInput(b);
            while(!def.needsInput())
                deflate();
         * Standard write routine. Defined by {@link java.io.OutputStream}.
         * Can only be used once openEntry has defined the file.
         * @param b  Bytes to write
        public void write(int b) throws IOException{
            oneByte[0] = (byte)b;
            crcAcc.update(b);
            write(oneByte, 0, 1);
         *  Standard write routine. Defined by {@link java.io.OutputStream}.
         * Can only be used once openEntry has defined the file.
         * @param b  Bytes to write
         * @param off Start offset
         * @param len Byte count
        public void write(byte[] b, int off, int len) throws IOException{
            if(entryInProgress == null)
                throw new IllegalStateException("Must call openEntry before writing");
            crcAcc.update(b, off, len);
            def.setInput(b, off, len);
            while(!def.needsInput())
                deflate();
        * Gets a buffer full of coded data from the deflater and writes it to archive.
        private void deflate() throws IOException {
            int len = def.deflate(deflateBuf);
            totalCompressed += len;
            if(len > 0)
                archive.write(deflateBuf, 0, len);

  • How to unzip a zip file within another zip file

    I've got code that successfully processes a file within a zip file.
    But now the zip file can also contain other zip files. How can I
    process a zip nested within a zip without actually extracting the
    files? It looks like I need a ZipFile object to be able to take
    advantage of the zip classes for reading zip entries. But the
    ZipFile methods want as an argument an actual file, as opposed
    to some object in memory. I can read the 'inner' zip file into a
    ZipInputStream object, but then how do I make that available for
    processing as a ZipFile? I've searched all over and cannot find
    anything anywhere that talks about working with nested zip files.
    Does anyone have any sample code that does this? Thanks!

    I have successfully done it.
    You cannot have the code - it is proprietary.
    However here are a few pointers:
    o Use ZipStreams rather than ZipFile.
    o ZipStream is just a filter on a stream, so you can have a zipstream open, read a ZipEntry, then ask for a substream for the stuff up to the next ZipEntry. Put a second ZipStream on that substream.
    o As I recall you have to watch out that your inner ZipStream does not do a close. (Everything will get closed.) Instead, there is another ZipStream method that will close without closing all the underlying streams.
    Hope this helps.

  • Can't open the Zipped file

    Hi
    I am making a zip file using GZIPOutputStream. But I am not able to open the zip file that is created using win zip.The size of the zipped file is 81 KB and the input file is 3,245 KB.I have closed all the streams still I am not able to figure out the problem.Any idea where I am going wrong ? Any help would be greatly appreciated.
    Here my code goes:
    import java.util.zip.*;
    import java.io.*;
    public class ZipFile
         public static void main(String[] args) throws FileNotFoundException,IOException
              ZipFile("D:\\Java\\Test\\INPUTXML_bkp_1.xml");
         public static String ZipFile(String fileName) throws FileNotFoundException,IOException
              String name = fileName.substring(fileName.lastIndexOf('\\') +1 ,fileName.lastIndexOf('.'));
              String filePath = fileName.substring(0,fileName.indexOf(name));
              String newFileName = new StringBuffer(name).append(".zip").toString();
              FileOutputStream outputStream = new FileOutputStream(newFileName);
              GZIPOutputStream zipOutputStream = new GZIPOutputStream(outputStream);
              FileInputStream inputStream = new FileInputStream(fileName);
              byte[] temp = new byte[10000000];
              int counter = inputStream.read(temp,0,temp.length);
              zipOutputStream.write(temp,0,counter);
              inputStream.close();
              zipOutputStream.finish();
              zipOutputStream.close();
              return newFileName;
    Thanks
    Ritesh

    Thanks for the reply.
    I changed my code to look like this:
    import java.util.zip.*;
    import java.io.*;
    public class ZipFile
         public static void main(String[] args) throws FileNotFoundException,IOException
              ZipFile("D:\\Java\\Test\\INPUTXML_bkp_1.xml");
         public static String ZipFile(String fileName) throws FileNotFoundException,IOException
              String name = fileName.substring(fileName.lastIndexOf('\\') +1 ,fileName.lastIndexOf('.'));
              String filePath = fileName.substring(0,fileName.indexOf(name));
              String newFileName = new StringBuffer(name).append(".zip").toString();
              FileOutputStream outputStream = new FileOutputStream(newFileName);
              ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
              ZipEntry zipEntry = new ZipEntry(fileName);
              zipOutputStream.putNextEntry(zipEntry);
              zipOutputStream.finish();
              zipOutputStream.close();
              return newFileName;
    Now I can atleast open the zip file. But the problem is the size of the file is 0 kb. Probably because, I am not populating the Zip entry. Can u pls let me know how do I do that.
    Thanks
    Ritesh

  • Adding image to a zip file

    Hi all,
    I am trying to work out a servlet that creates an on-the-fly zip file. I am trying to add an image in this zip file and then I want to prompt user to download the created zip file. It is creating the zip file -it prompts the user and downloads the zip file... but when I open the downloaded zip file -the image is not found to be added in it. Please help, here is the code:
    package servlets;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.zip.*;
    import java.net.*;
    import java.util.*;
    public class CreateZipFile extends HttpServlet {
         byte b[] = new byte[300000];
         ByteArrayOutputStream bout = new ByteArrayOutputStream();
         ZipOutputStream zout = null;
         ServletOutputStream out = null;
         ServletContext servletContext = null;
         HttpServletResponse res=null;
         public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
              this.res=res;
              out=res.getOutputStream();
              servletContext=getServletContext();
              File f= new File(getServletContext().getRealPath(req.getContextPath()));
              String fs = System.getProperty("file.separator");
              addToZip_Image (f.getParentFile() + fs + ("images/thermorack.jpg"));
              System.out.println("ready");
              String zip = bout.toString();
              res.setContentType("application/zip");
              res.setHeader("Content-Disposition", "inline; filename=output_dd.zip;");
              System.out.println("finished");
              out.println(zip);
              out.flush();
         public void addToZip_Image(String img) throws ServletException, IOException
              System.out.println("image=" + img);
                   try {
                        FileInputStream input = new FileInputStream(img);
                        zout = new ZipOutputStream(new FileOutputStream(img));
                        zout.putNextEntry(new ZipEntry("image.jpg"));
                        int len;
                        while ((len = input.read(b)) > 0) {
                        zout.write(b, 0, len);
                        zout.closeEntry();
                        zout.close();
                        input.close();
                        System.out.println("closed");                    
                   } catch (Exception e) {
                        System.out.println("Exception occurred");
                        res.setContentType("text/html");
                        out.println("<html><head><title>Error</title></head>");
                        out.println("<body><b>");
                        out.println("An error has occured while processing "
                                  + "<br>");
                        out.println("Here is the exception: <br>" + e + "<br>");
                        e.printStackTrace(new PrintWriter(out));
                        out.println("</body>");
                        out.println("</html>");
    }

    You would need to purchase Stuffit Standard:
    http://my.smithmicro.com/mac/stuffit/index.html

  • Problem in deleting Zip files unzipped using java.util.zip

    I have a static methos for unzipping a zip file. after unzipping the file when i am trying to delete that file using File.delete()its not getting deleted. but when methods like exist(). canRead(), canWrite() methods are returning true what can be the possible problem ? i had closed all the streams after unzipping operation Please go through the following code.
    public static boolean unzipZipFile(String dir_name, String zipFileName) {
    try {
    ZipFile zip = new ZipFile(zipFileName);
    Enumeration entries = zip.entries();
    while (entries.hasMoreElements()) {
    ZipEntry entry = (ZipEntry) entries.nextElement();
    // got all the zip entries here
    // now has to process all the files
    // first all directories
    // then all the files
    if (entry.isDirectory()) {
    // now the directories are created
    File buf=new File(dir_name,entry.getName());
    buf.mkdirs();
    continue;
    }// now got the dirs so process the files
    entries = zip.entries();
    while(entries.hasMoreElements()) {
    // now to process the files
    ZipEntry entry = (ZipEntry) entries.nextElement();
    if (!entry.isDirectory()){
    File buf=new File(dir_name,entry.getName());
    copyInputStream(
    zip.getInputStream(entry),
    new BufferedOutputStream(
    new FileOutputStream(buf)));}
    } catch (IOException e) {
    e.printStackTrace();
    return false;
    return true;
    now i am trying to call this method to unzip a zip file
    public static void main (String arg[]){
    unzipZipFile("C:/temp","C:/tmp.zip");
    java.io.File filer = new File("C:/tmp.zip");
    System.out.println (filer.canRead());
    System.out.println (filer.canWrite());
    System.out.println (filer.delete());
    Please tell me where my program is going wrong ?

    Thanks .. the problem is solved... i was not closing the Zip file .. rather i was trying to close all the other streams that i used for IO operaion ... thanks a lot

  • Email internal table as zip file

    Hello everyone
    I spent several days to have a full example on how to convert an internal table has ZIP file than send it by email.
    I found several example to upload file from the OS and than convert it to ZIP to save it after. But nothing from the current internal email.
    So, for the benefit of everybody who that can interrest, here is the code I did. Feel free to optimize it and post the new version here.
    ===========================================
    Moderator message - Please respect the 2,500 character maximum when posting. Post only the relevant portions of code
    ==========================================
    Regards
    dstj
    Edited by: Rob Burbank on Feb 12, 2010 2:09 PM

    Hello Daniel,
    Thank you very much for this post, it is quite helpful. However, I have followed your template very closely and my file will not send. I am not an advaned ABAP programmer, but have a good knowledge of programming in general...here's a bit of my code related to this...
    *-Create table body
      LOOP AT (internal table) INTO (structure)
      (Fill lv_line with one line of string based on structure)
        CALL FUNCTION 'SCMS_STRING_TO_XSTRING'
          EXPORTING
            text = lv_line
          IMPORTING
            buffer = lv_xline
        CONCATENATE lv_xcontent lv_xline INTO lv_xcontent IN BYTE MODE.
      ENDLOOP.
    *-Create zip xstring
      CREATE OBJECT lo_zipper.
      CALL METHOD lo_zipper->add
        EXPORTING
          name = 'AHReport.zip'
          content = lv_xcontent.
      CALL METHOD lo_zipper->save
        RECEIVING
          zip = lv_xzipcontent.
    *-Convert zip xstring to binary
      CALL FUNCTION 'SCMS_XSTRING_TO_BINARY'
        EXPORTING
          buffer = lv_xzipcontent
        TABLES
          binary_tab = lt_data.
    *-    Add attachment     
          TRY.
            CALL METHOD l_document->add_attachment
                EXPORTING
                  i_attachment_type = 'ZIP'
                  i_attachment_subject = 'Report'
                  i_att_content_hex = lt_data.
            CATCH cx_document_bcs.
          ENDTRY.
    Any help would be very much appreciated, ty.

Maybe you are looking for

  • What is the Fix?

    I was really excited to see the free update to the opertaing system and pretty happy when things like iBooks and a new version of iMovies downloaded to my Mac.  However, I am still trying to wrap my head around the reasonsing behind the podcast funct

  • I updated to iOS 7 & now I cannot bring up new URL page.  How do I fix this?

    I updated to iOS 7 & now I cannot bring up a new Web page.  How do I fix this?

  • Internal Orders - AuC

    Experts, We have a requirement, where in the creation of an Internal Order for a certain Order Type, would create an AuC also automatically. Any ways we can achieve this task. All answers/inputs/thoughts would be duly appreciated and rewarded with po

  • Conflicting dependency when installing ABAP in Eclipse Kepler

    I have installed SAP HANA Studio Version: 1.0.48 Build id: 201301130825 (372847) I downloaded and installed "eclipse-standard-kepler-SR2-win32-x86_64" I am following the instruction in "ADT_740_installation.pdf" I try to add the components through ht

  • Deleting a Page

    I accidnetally scanned the same page twice, and need to delete one of them (after having "finished" the can). Please advise.