5

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?

MWiesner
  • 8,868
  • 11
  • 36
  • 70
Shubham Kadlag
  • 2,248
  • 1
  • 13
  • 32
  • 3
    Yes. https://docs.oracle.com/javase/10/docs/api/java/io/InputStream.html#transferTo(java.io.OutputStream) – Stephen C May 17 '18 at 14:45
  • Ohh. So it was added in java 9. – Shubham Kadlag May 17 '18 at 14:49
  • 1
    https://stackoverflow.com/a/37681322/2711488 And for the special case of `ByteArrayOutputStream`, there always has been [`writeTo(OutputStream)`](https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#writeTo(java.io.OutputStream)) – Holger May 17 '18 at 15:54

1 Answers1

5

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.

ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
Ruslan Akhundov
  • 2,178
  • 4
  • 20
  • 38