Should I use DataInputStream or BufferedInputStream

Use a normal InputStream (e.g. FileInputStream) wrapped in an InputStreamReader and then wrapped in a BufferedReader - then call readLine on the BufferedReader.

DataInputStream is good for reading primitives, length-prefixed strings etc.


InputStream: Base class to read byte from stream (network or file ), provide ability to read byte from the stream and delete the end of the stream.

DataInputStream: To read data directly as a primitive datatype.

BufferInputStream: Read data from the input stream and use buffer to optimize the speed to access the data.


The two classes are not mutually exclusive - you can use both of them if your needs suit.

As you picked up, BufferedInputStream is about reading in blocks of data rather than a single byte at a time. It also provides the convenience method of readLine(). However, it's also used for peeking at data further in the stream then rolling back to a previous part of the stream if required (see the mark() and reset() methods).

DataInputStream/DataOutputStream provides convenience methods for reading/writing certain data types. For example, it has a method to write/read a UTF String. If you were to do this yourself, you'd have to decide on how to determine the end of the String (i.e. with a terminator byte or by specifying the length of the string).

This is different from BufferedInputStream's readLine() which, as the method sounds like, only returns a single line. writeUTF()/readUTF() deal with Strings - that string can have as many lines it it as it wants.

BufferedInputStream is suitable for most text processing purposes. If you're doing something special like trying to serialize the fields of a class to a file, you'd want to use DataInput/OutputStream as it offers greater control of the data at a binary level.

Hope that helps.


You can always use both:

final InputStream inputStream = ...;
final BufferedInputStream bufferedInputStream =
        new BufferedInputStream(inputStream);
final DataInputStream dataInputStream =
        new DataInputStream(bufferedInputStream);

Tags:

Java

Io