Search code examples
javaxslttransformzipinputstream

How to prevent ZipInputStream from being closed by after a XSLT transform?


I have a ZipInputStream that contains a number of XML files that I want to apply a transform to. The following piece of code loads the XSLT and ZIP files and loops through the ZIP entries, attempting to apply the transform to each one. However it appears the transform function is closing the input stream after performing the transform, causing the getNextEntry() function to fail because the stream is closed.

Is there is a simple way around this problem (to keep the input stream open allowing the ZipInputStream to move to the next entry) or am I missing something more fundamental here?

TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(xsltFileName));

FileInputStream fis = new FileInputStream(fileName);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze = null;

while ((ze = zis.getNextEntry()) != null)
{
    String newFileName = ze.getName();
    transformer.transform(new StreamSource(zis), new StreamResult(new FileOutputStream(newFileName)));
}

I have attempted to search for a solution but don't seem to be coming up with anything that makes sense. I'd appreciate any ideas or feedback.


Solution

  • One possible solution is to extend ZipInputStream (it's not final) and override the close method to do nothing. Of course you need to make sure then to close it your self. You can do that with a second custom close method that simply calls super.close().

    class MyZIS extends ZipInputStream {
    
        public MyZIS(InputStream in) {
            super(in);
        }
    
        @Override
        public void close() throws IOException {
        }
    
        public void myClose() throws IOException {
            super.close();
        }
    }