InputStream.transferTo()
Copy an InputStream to an OutputStream in one call.
Code Comparison
✕ Java 8
byte[] buf = new byte[8192];
int n;
while ((n = input.read(buf)) != -1) {
output.write(buf, 0, n);
}
✓ Java 9+
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()
Since JDK
9
Difficulty
beginner
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.