Skip to content

Commit 7753e01

Browse files
committed
Bring feature parity to the Java9 version of Streams
1 parent d368952 commit 7753e01

File tree

1 file changed

+48
-3
lines changed
  • libs/elasticsearch-core/src/main/java9/org/elasticsearch/core/internal/io

1 file changed

+48
-3
lines changed

libs/elasticsearch-core/src/main/java9/org/elasticsearch/core/internal/io/Streams.java

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,7 @@
2525

2626
/**
2727
* Simple utility methods for file and stream copying.
28-
* All copy methods use a block size of 4096 bytes,
29-
* and close all affected streams when done.
28+
* All copy methods close all affected streams when done.
3029
* <p>
3130
* Mainly for use within the framework,
3231
* but also useful for application code.
@@ -43,6 +42,52 @@ public abstract class Streams {
4342
* @throws IOException in case of I/O errors
4443
*/
4544
public static long copy(InputStream in, OutputStream out) throws IOException {
46-
return in.transferTo(out);
45+
boolean success = false;
46+
try {
47+
final long byteCount = in.transferTo(out);
48+
out.flush();
49+
success = true;
50+
return byteCount;
51+
} finally {
52+
if (success) {
53+
Exception ex = null;
54+
try {
55+
in.close();
56+
} catch (IOException | RuntimeException e) {
57+
ex = e;
58+
}
59+
60+
try {
61+
out.close();
62+
} catch (IOException | RuntimeException e) {
63+
if (ex == null) {
64+
ex = e;
65+
} else {
66+
ex.addSuppressed(e);
67+
}
68+
}
69+
70+
if (ex != null) {
71+
if (ex instanceof IOException) {
72+
throw (IOException) ex;
73+
} else {
74+
throw (RuntimeException) ex;
75+
}
76+
}
77+
} else {
78+
try {
79+
in.close();
80+
} catch (IOException | RuntimeException e) {
81+
// empty
82+
}
83+
84+
try {
85+
out.close();
86+
} catch (IOException | RuntimeException e) {
87+
// empty
88+
}
89+
}
90+
}
91+
4792
}
4893
}

0 commit comments

Comments
 (0)