Skip to content

Commit 222665a

Browse files
Fix Java11 Streams Class Copy (#60641)
In #60608 we missed aligning the Java11 version of this class and this is breaking BwC tests now. This commit aligns Java11 and Java8 versions of it again.
1 parent 20ae1b7 commit 222665a

File tree

1 file changed

+38
-7
lines changed
  • libs/core/src/main/java11/org/elasticsearch/core/internal/io

1 file changed

+38
-7
lines changed

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

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,26 +32,57 @@
3232
*/
3333
public abstract class Streams {
3434

35+
private static final ThreadLocal<byte[]> buffer = ThreadLocal.withInitial(() -> new byte[8 * 1024]);
36+
3537
/**
36-
* Copy the contents of the given InputStream to the given OutputStream.
37-
* Closes both streams when done.
38+
* Copy the contents of the given InputStream to the given OutputStream. Optionally, closes both streams when done.
3839
*
39-
* @param in the stream to copy from
40-
* @param out the stream to copy to
40+
* @param in the stream to copy from
41+
* @param out the stream to copy to
42+
* @param close whether to close both streams after copying
43+
* @param buffer buffer to use for copying
4144
* @return the number of bytes copied
4245
* @throws IOException in case of I/O errors
4346
*/
44-
public static long copy(final InputStream in, final OutputStream out) throws IOException {
47+
public static long copy(final InputStream in, final OutputStream out, byte[] buffer, boolean close) throws IOException {
4548
Exception err = null;
4649
try {
47-
final long byteCount = in.transferTo(out);
50+
long byteCount = 0;
51+
int bytesRead;
52+
while ((bytesRead = in.read(buffer)) != -1) {
53+
out.write(buffer, 0, bytesRead);
54+
byteCount += bytesRead;
55+
}
4856
out.flush();
4957
return byteCount;
5058
} catch (IOException | RuntimeException e) {
5159
err = e;
5260
throw e;
5361
} finally {
54-
IOUtils.close(err, in, out);
62+
if (close) {
63+
IOUtils.close(err, in, out);
64+
}
5565
}
5666
}
67+
68+
/**
69+
* @see #copy(InputStream, OutputStream, byte[], boolean)
70+
*/
71+
public static long copy(final InputStream in, final OutputStream out, boolean close) throws IOException {
72+
return copy(in, out, buffer.get(), close);
73+
}
74+
75+
/**
76+
* @see #copy(InputStream, OutputStream, byte[], boolean)
77+
*/
78+
public static long copy(final InputStream in, final OutputStream out, byte[] buffer) throws IOException {
79+
return copy(in, out, buffer, true);
80+
}
81+
82+
/**
83+
* @see #copy(InputStream, OutputStream, byte[], boolean)
84+
*/
85+
public static long copy(final InputStream in, final OutputStream out) throws IOException {
86+
return copy(in, out, buffer.get(), true);
87+
}
5788
}

0 commit comments

Comments
 (0)