[jira] [Created] (IO-593) copyToFile incorrectly closes input stream

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

[jira] [Created] (IO-593) copyToFile incorrectly closes input stream

JIRA jira@apache.org
Martijn Dwars created IO-593:
--------------------------------

             Summary: copyToFile incorrectly closes input stream
                 Key: IO-593
                 URL: https://issues.apache.org/jira/browse/IO-593
             Project: Commons IO
          Issue Type: Bug
          Components: Utilities
    Affects Versions: 2.6
         Environment: macOS 10.14
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
            Reporter: Martijn Dwars


h3. Description of the Problem

FileUtils.copyToFile is supposed to _not_ close the input stream. According to the documentation: 
{quote}The \{@code source} stream is left open, e.g. for use with \{@link java.util.zip.ZipInputStream ZipInputStream}.
{quote}
In 2.5 [FileUtils.java:1551-1559|https://github.com/apache/commons-io/blob/commons-io-2.5/src/main/java/org/apache/commons/io/FileUtils.java#L1551-L1559] this was implemented correctly. In 2.6 [FileUtils.java:1528-1531|https://github.com/apache/commons-io/blob/commons-io-2.6-RC3/src/main/java/org/apache/commons/io/FileUtils.java#L1528-L1531] both resources are used in a try-with-resources block, which closes the input stream.
----
h3. How to Reproduce?

We discovered this bug in the following code:
{code:java}
try (JarInputStream jarStream = new JarInputStream(fileInputStream)) {
  JarEntry entry = jarStream.getNextJarEntry();
  while (jarStream.available() != 0) {
    File file = new File(directory, entry.getName());

    if (!entry.isDirectory()) {
      FileUtils.copyToFile(jarStream, file);
    }
    entry = jarStream.getNextJarEntry();
  }
}
{code}
At some point, jarStream.getNextJarEntry(); throws an exception because the stream is closed:
{code:java}
Caused by: java.io.IOException: Stream closed
        at java.util.zip.ZipInputStream.ensureOpen(ZipInputStream.java:67)
        at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:116)
        at java.util.jar.JarInputStream.getNextEntry(JarInputStream.java:142)
        at java.util.jar.JarInputStream.getNextJarEntry(JarInputStream.java:179)
{code}
You may need to read from a sufficiently large JAR to expose the bug.
----
h3. How to Fix?

Fixing this is relatively easy: do not alias `in = source` in the try-with-resources block. Let me know if this bug gets acknowledged, I would be happy to work on a fix.



--
This message was sent by Atlassian JIRA
(v7.6.3#76005)