DataInputStream and DataOutputStream for primitive data

In java, basic input-output stream provides a method for reading & writing bytes or character in a file.

If we want to read-write primitive data typa (such as int , float etc.) than we can use filter classes to filter data in the original stream.

DataInputStream & DataOutputStream are two filter classes used for creating “data streams” for handling primitive data type.

1 DataInputStream Class

In java DataInputStream class is used to allow application to read primitive data from different sources.

DataInputStream is a sub type of FilterInputStream.

A. DataInputStream Constructor

Sr NoConstructor
1DataInputStream​(InputStream in)
Take InputStream object to create DataInputStream

Constructor call of DataInputStream

FileInputStream i = new FileInputStream("A.txt"); //open file A for read        
DataInputStream I = new DataInputStream(i);

B Methods in DataInputStream

Following are the methods of DataInputStream

Sr NoMethod
1public final int read(byte[] b) throws IOException
Reads number of bytes from input stream and store in buffered array b
2public final int read(byte[] b, int off, int len) throws IOException
Reads up to len bytes from input stream and store in buffered array b
3public final boolean readBoolean() throws IOException
Reads one input byte and return true if byte is non zero, else false
4public final byte readByte() throws IOException
Reads and return one input byte
5public final char readChar() throws IOException
Reads two input byte and return a char
6public final double readDouble() throws IOException
Reads eight input byte and return a double value
7public final float readFloat() throws IOException
Reads four input bytes and return a float value
8public final void readFully(byte[] b) throws IOException
Reads some bytes from input stream and store in buffer array b
9public final int readInt() throws IOException
Reads four input bytes and return a integer value
10public final long readLong() throws IOException
Reads eight input bytes and returns a long value
11public final short readShort() throws IOException
Reads one input bytes and returns a short value
12public final int readUnsignedByte() throws IOException
Reads two byte and return unsigned byte value
13public final String readUTF() throws IOException
Reads a string that has been encoded in modified utf-8 format
15public static final String readUTF(DataInput in) throws IOException
Reads from a stream that has been encoded in modified utf-8 format
16public final int skipBytes(int n) throws IOException
Makes attempt to skip n bytes of data from input stream

Example: Write a program to write & read a primitive data on a same file.