4

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.

Jus12
  • 17,058
  • 25
  • 90
  • 151

1 Answers1

3

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.

james_bond
  • 6,436
  • 2
  • 25
  • 32
  • Is it necessary to close `fos` in the example above? – Jus12 May 16 '11 at 02:53
  • 1
    According to the javadoc, closing `bos` will close `fos`. See http://download.oracle.com/javase/6/docs/api/java/io/FilterOutputStream.html#close(). – huynhjl May 16 '11 at 03:13