Suvam Roy Suvam Roy - 3 years ago 82
Java Question

When should we use BufferedInputStream,FileInputStream or DataInputStream?

I'm confused the above mentioned classes. When to use what? From my perspective every thing that comes in, is in the form of stream in java right? so which one is to use in what case to make the input more efficient? Also answer please can I use DataInputStream or BufferedInputStream in case of reading content from files?

JDC JDC
Answer Source

Short and simple:

FileInputStream

Is used for reading from files.

DataInputStream

Is used for reading in primitive Java types (that you might have written using a DataOutputStream) and provides convenience methods for that purpose, e.g. writeInt().

See the JavaDoc:

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way.

BufferedInputStream

Is used to do buffered block reads from an InputStream (instead of single bytes) and increases performance if reading small chunks of data. Most of the time you want to use it for text processing.


Of course you can combine those.

Example of writing primitive Java types to a file:

FileOutputStream write = new FileOutputStream 
DataOutputStream out = new DataOutputStream(write);
out.writeInt(10);
write.close();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download