Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataOutputStream() VS DataOutputStream(new BufferedOutputStream())

Tags:

java

io

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 ?

like image 382
Pacerier Avatar asked Nov 13 '11 05:11

Pacerier


People also ask

What is the difference between DataOutputStream and FileOutputStream?

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.

When should I use DataOutputStream?

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.

What is BufferedOutputStream in Java?

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.


1 Answers

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.

like image 67
Ted Hopp Avatar answered Sep 17 '22 14:09

Ted Hopp