Search code examples
javainputstreamreaderjava-10

What is java.io.Reader transferTo(java.io.Writer) method in Java 10 ? Is there a similar method for InputStream?


I read the Java 10 documentation on java.io.Reader.transferTo(...) and it says:

Reads all characters from this reader and writes the characters to the given writer in the order that they are read

The method transferTo in Reader would be very useful as currently it is quite verbose to copy data from reader to writer. As we mostly use InputStream and OutputStream in real life applications, is there a similar method for them?


Solution

  • There is such method in InputStream since Java 9: InputStream.transferTo()

    Also, for earlier versions of JDK, there is IOUtils.copy(InputStream input, OutputStream output) in apache-commons-io library.

    Documentation says:

    Copies bytes from an InputStream to an OutputStream

    So, it should do the same thing.