InputStream.transferTo()
Copy an InputStream to an OutputStream in one call.
Porównanie kodu
✕ 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ć.
Dlaczego nowoczesne podejście wygrywa
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
Wsparcie JDK
InputStream.transferTo()
Dostępne
Widely available since JDK 9 (Sept 2017)
Jak to działa
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.
Powiązana dokumentacja