The code at Java Tutorials showed an example of using DataOutputStream
class and DataInputStream
class.
A snippet of the code looks like this:
//..
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));
//..
in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
//..
I was wondering why is it required to create a new BufferedOutputStream
when we create a new DataOutputStream
?
Isn't it redundant since this alternative works as well? : new DataOutputStream(new FileOutputStream(dataFile));
As this page claims, DataStreams already provides a buffered file output byte stream. So is "double-buffering" really required?
I've modified the 2 lines of code (output and input), taking away the BufferedOutputStream
and BufferedInputStream
and everything seems to work just fine, so I was wondering what is the purpose of the BufferedOutputStream
and BufferedInputStream
?
DataOutputStream – an output stream that contains methods for writing data of standard types defined in Java; FileInputStream – an input stream that contains methods that read data from a file; FileOutputStream – An output stream that contains methods that write data to a file.
A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.
BufferedOutputStream(OutputStream out) Creates a new buffered output stream to write data to the specified underlying output stream. BufferedOutputStream(OutputStream out, int size) Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.
Wrapping the FileOutputStream in a BufferedOutputStream will generally speed up the overall output of your program. This will only be noticeable if you are writing large amounts of data. The same thing goes for wrapping an InputStream in a BufferedInputStream. The use of buffers will only affect efficiency, not correctness.
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