GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — InputStream.transferTo() | java.evolved
I/O
Beginner
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);
See a problem with this code? Let us know.
Why the modern way wins
📏
One lineReplace the entire read/write loop with one method call. ⚡
OptimizedInternal buffer size is tuned for performance. 🛡️
No bugsNo 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
Proof
Related patterns
I/O
Beginner
Writing filesJava 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
);
JDK 11+
→
I/O
Advanced
Deserialization filtersJava 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();
JDK 9+
→
I/O
Beginner
Try-with-resources improvementJava 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);
}
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. |