DataInputStream
Last updated
Last updated
The Java DataInputStream class, java.io.DataInputStream
, enables you to read Java primitives (int, float, long etc.) from an InputStream
instead of only raw bytes. You wrap an InputStream
in a DataInputStream
and then you can read Java primitives via ' the DataInputStream
. That is why it is called DataInputStream - because it reads data (numbers) instead of just bytes.
The DataInputStream
is handy if the data you need to read consists of Java primitives larger than one byte each, like int, long, float, double etc. The DataInputStream
expects the multi byte primitives to be written in network byte order (Big Endian - most significant byte first).
Often you will use a Java DataInputStream to read data written by a Java DataOutputStream.
The Java DataInputStream class is a subclass of InputStream, so DataInputStream also has the basic read methods that enable you to read a single byte or an array of bytes from the underlying InputStream, in case you need that. In this Java DataInputStream tutorial I will only cover the extra methods the DataInputStream has, though.
One issue to keep in mind when reading primitive data types is, that there is no way to distinguish a valid int value of -1 from the normal end-of-stream marker. That basically means, that you cannot see from the primitive value returned if you have reached end-of-stream. Therefore you kind of have to know ahead of time what data types to read, and in what sequence. In other words, you need to know ahead of time what data you can read from the DataInputStream.
Here is a Java DataInputStream
example:
First a DataInputStream
is created with a FileInputStream
as source for its data. Second, Java primitives are read from the DataInputStream
.
You create a Java DataInputStream via its constructor. When you do so, you pass an InputStream as parameter from which the primitive data types are to be read. Here is an example of creating a Java DataInputStream:
As mentioned earlier, the DataInputStream
class is often used together with a DataOutputStream
. Therefore I just want to show you an example of first writing data with a DataOutputStream
and then reading it again with a DataInputStream
. Here is the example Java code:
This example first creates a DataOutputStream
and then writes an int
, float
and a long
value to a file. Second the example creates a DataInputStream
which reads the int
, float
and long
value in from the same file.