โ— Shell
clean mode source โ†—

InputStream.transferTo()

Home / I/O / InputStream.transferTo()

Code Comparison

byte[] buf = new byte[8192];
int n;
while ((n = input.read(buf)) != -1) {
    output.write(buf, 0, n);
}
input.transferTo(output);

Why the modern way wins

๐Ÿ“

One line

Replace the entire read/write loop with one method call.

โšก

Optimized

Internal buffer size is tuned for performance.

๐Ÿ›ก๏ธ

No bugs

No off-by-one errors in buffer management.

Old Approach

Manual Copy Loop

Modern Approach

transferTo()

JDK Support

InputStream.transferTo()

Available

Widely available since JDK 9 (Sept 2017)

How it works

transferTo() reads all bytes from the input stream and writes them to the output stream. No buffer management, no loop. It uses an optimized internal buffer.

Related Documentation

Proof