Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read one stream into another? [duplicate]

Tags:

java

FileInputStream in = new FileInputStream(myFile); ByteArrayOutputStream out = new ByteArrayOutputStream(); 

Question: How can I read everything from in into out in a way which is not a hand-crafted loop with my own byte buffer?

like image 647
Konrad Garus Avatar asked Feb 07 '11 09:02

Konrad Garus


People also ask

What are the different ways to read data from one stream and write to another?

Among these, you can read the contents of a file using Scanner, BufferedReader and, FileReader classes. In the same way, you can write data into a file using BufferedWriter, FileOutputStream, FileWriter.

How do I write from one stream to another?

CopyTo(Stream, Int32) Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied.

Can I reuse Java stream?

So it is very important to remember that Java 8 streams can't be reused.


1 Answers

Write one method to do this, and call it from everywhere which needs the functionality. Guava already has code for this, in ByteStreams.copy. I'm sure just about any other library with "general" IO functionality has it too, but Guava's my first "go-to" library where possible. It rocks :)

like image 81
Jon Skeet Avatar answered Sep 19 '22 01:09

Jon Skeet