diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java index 7e2d546ec..695be27f2 100644 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java +++ b/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java @@ -131,12 +131,28 @@ public final class ZipPackage extends Package { // some zips can't be opened via ZipFile in JDK6, as the central directory // contains either non-latin entries or the compression type can't be handled // the workaround is to iterate over the stream and not the directory - FileInputStream fis; + FileInputStream fis = null; + ThresholdInputStream zis = null; try { fis = new FileInputStream(file); - ThresholdInputStream zis = ZipHelper.openZipStream(fis); + zis = ZipHelper.openZipStream(fis); ze = new ZipInputStreamZipEntrySource(zis); } catch (IOException e2) { + if (zis != null) { + try { + zis.close(); + } catch (IOException e3) { + throw new InvalidOperationException("Can't open the specified file: '" + file + "'"+ + " and couldn't close the file input stream", e); + } + } else if (fis != null) { + try { + fis.close(); + } catch (IOException e3) { + throw new InvalidOperationException("Can't open the specified file: '" + file + "'"+ + " and couldn't close the file input stream", e); + } + } throw new InvalidOperationException("Can't open the specified file: '" + file + "'", e); } } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestZipPackage.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestZipPackage.java index d733ade32..7f174e07a 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestZipPackage.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestZipPackage.java @@ -25,8 +25,10 @@ import static org.junit.Assert.fail; import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; @@ -174,4 +176,24 @@ public class TestZipPackage { SlideShow ppt = SlideShowFactory.create(f, null, true); ppt.close(); } + + @Test + public void testClosingStreamOnException() throws IOException { + InputStream is = OpenXML4JTestDataSamples.openSampleStream("dcterms_bug_56479.zip"); + File tmp = File.createTempFile("poi-test-truncated-zip", ""); + OutputStream os = new FileOutputStream(tmp); + for (int i = 0; i < 100; i++) { + os.write(is.read()); + } + os.flush(); + os.close(); + is.close(); + + try { + OPCPackage.open(tmp, PackageAccess.READ); + } catch (Exception e) { + } + assertTrue("Can't delete tmp file", tmp.delete()); + + } }