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?
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.
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.
So it is very important to remember that Java 8 streams can't be reused.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With