GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — InputStream.transferTo() | java.evolved

Home / I/O / InputStream.transferTo()
I/O Beginner

InputStream.transferTo()

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Copy an InputStream to an OutputStream in one call.

I/O
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);
Share 𝕏
See a problem with this code? Let us know.
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.

Related Documentation
InputStream.transferTo() ↗
Proof
View proof source ↗
Related patterns
I/O Beginner

Writing files

Java 8
try (FileWriter fw =
        new FileWriter("out.txt");
    BufferedWriter bw =
        new BufferedWriter(fw)) {
    bw.write(content);
}
Java 11+
Files.writeString(
    Path.of("out.txt"),
    content
);
Hover to see modern ➜
JDK 11+ →
I/O Advanced

Deserialization filters

Java 8
// Dangerous: accepts any class
ObjectInputStream ois =
    new ObjectInputStream(input);
Object obj = ois.readObject();
// deserialization attacks possible!
Java 9+
ObjectInputFilter filter =
    ObjectInputFilter.Config
    .createFilter(
        "com.myapp.*;!*"
    );
ois.setObjectInputFilter(filter);
Object obj = ois.readObject();
Hover to see modern ➜
JDK 9+ →
I/O Beginner

Try-with-resources improvement

Java 8
Connection conn = getConnection();
// Must re-declare in try
try (Connection c = conn) {
    use(c);
}
Java 9+
Connection conn = getConnection();
// Use existing variable directly
try (conn) {
    use(conn);
}
Hover to see modern ➜
JDK 9+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.