Copy Streams In Java 9 With The InputStream.transferTo() Method

1. Overview

This quick tutorial is going to cover how to use the InputStream.transferTo(), a new method that has been added to the InputStream class from Java 9,  to copy data from input streams to output streams in Java.

2. The InputStream.transferTo(OutputStream) Method

Firstly, let’s take a look at the syntax of the InputStream.transferTo(OutputStream) method which reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read:

Parameters:
out – the output stream, non-null

Returns:
The number of bytes transferred
Throws:
IOException – if an I/O error occurs when reading or writing.
NullPointerException – if out is null.

3. Copy Streams In Java 9 With InputStream.transferTo() Example

Let’s take a look at an example how we use the transferTo() method to copy data from input streams to output streams in Java 9:

We have just copied the content of the application.properties to the application.properties.bk file by using the transferTo() method. Notice that we have used to effective try-with-resources supported in Java 9. And next, let’s see the same example implemented with the earlier versions of Java:

4. Conclusions

The tutorial has illustrated how to use the InputStream.transferTo() method  to copy data from input streams to output streams in Java 9. Notice that the transferTo() method is available from Java 9, to achieve the same purpose with previous versions of Java, there are several methods, and one of them is to use the transferTo() method defined in the FileChannel interface.

The sample source code presented in this tutorial is available on my Github project. It’s a Maven based project, it will be easy to be imported into IDEs such as Eclipse, IntelliJ, etc.

Below are other related tutorials for your references:

Java 9 Tutorial

Java 9 JShell Cheat Sheet

Private Interface Methods In Java 9

Install Oracle Java 9 on CentOS, RHEL 7

Install Oracle Java 9 on Ubuntu 16.04 LTS (Xenial Xerus)

Set Up Eclipse, IntelliJ And NetBeans For Java 9

Java 9 Example With Maven And JUnit 5

Create Immutable Lists In Java 9 By Static Factory Methods

Java 9 – New Methods Of The Optional Class

Streams API Updates In Java 9

How To Compare Arrays In Java 9

Java 9 HTTP/2 Client API Example

Java 9 – Effectively Final Variables In try-with-resources