Search code examples
javascalabufferedinputstream

BufferedStream chaining Scala (or Java)


Assuming that I have to write to a binary file. I can use the following code

val fos = new FileOutputStream("fileName")

and then use

fos.write(bytes)

Is it always a good idea to chain it with a buffered stream? as in:

val fos = new FileOutputStream("FileName")
val bos = new BufferedOutputStream(fos)

Does the same rule hold for FileInputStream?

Is it necessary to close fos in the end (in the chained version)?

EDIT: Found the answer to the last question. It is not necessary to close the inner streams, as mentioned here.


Solution

  • Depends on the type of data you want to write. BufferedStream is meant to be used when you don't want the underlying system (the one that performs the actual write) to be called for every byte written, while FileOutputStream is meant to be used when you want to write raw bytes such as when writing an image.