I/O Początkujący

Copy an InputStream to an OutputStream in one call.

✕ 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);
Widzisz problem z tym kodem? Daj nam znać.
📏

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.

Stare podejście
Manual Copy Loop
Nowoczesne podejście
transferTo()
Od JDK
9
Poziom trudności
Początkujący
InputStream.transferTo()
Dostępne

Widely available since JDK 9 (Sept 2017)

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.

Udostępnij 𝕏 🦋 in