Вы находитесь на странице: 1из 3

DataInputStream

1. The Java DataInputStream class enables to read Java primitives (int, float, long, etc.…) from an
InputStream instead of only raw bytes.

2. You wrap an InputStream in a DataInputStream and then you can read Java primitives from the
DataInputStream.

3. DataInputStream reads data (numbers) instead of just bytes.

4. 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.….

5. The DataInputStream expects the multibyte primitives to be written in network byte order
(BigEndian-> Most significant Byte First).

Java DataInputStream class Methods

Method Description

int read(byte[] b) It is used to read the number of bytes from the input stream.

int read(byte[] b, int It is used to read len bytes of data from the input stream.
off, int len)

int readInt() It is used to read input bytes and return an int value.

byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.

double readDouble() It is used to read eight input bytes and returns a double value.

boolean It is used to read one input byte and return true if byte is non
readBoolean() zero, false if byte is zero.

int skipBytes(int x) It is used to skip over x bytes of data from the input stream.

String readUTF() It is used to read a string that has been encoded using the UTF-8 format.

void readFully(byte[] It is used to read bytes from the input stream and store them into
b) the buffer array.

void readFully(byte[] It is used to read len bytes from the input stream.
b, int off, int len)

*****Note: inputStream.read(byte[] b,int offset,int len);


1. Reads up to len bytes of data from the InputStream into an array of bytes.
2. This method blocks until input data is available, end of file is detected, or an exception is
thrown.
3. If len is zero, then no bytes are read and 0 is returned.
4. If no byte is available because the stream is at the end of file, the value ‘-1’ is returned.
5. example: abcde :- inputStream.read(buffer,1,5) => reads 5 bytes at a time and discards 0th index of
the incoming stream.

i. number of byte arrays : 1

ii. a is discarded

iii. the resulting array consists of bcde => byte[0] = b, byte[1] = c, byte[2] = d, byte[3] = e

6. example : abcdefghij : InputStream.read(buffer,1,5) => reads 5 bytes at a time and discards 0th index
of the incoming stream.

i. number of byte arrays : 2

ii. first array => a is discarded.

iii. the resulting 1st array => bcde => byte[0] = b, byte[1] = c, byte[2] = d, byte[3] = e
iv. second array => f is discarded

v. the resulting 2nd array => ghij => byte[0] = g, byte[1] = h, byte[2] = i, byte[3] = j

Вам также может понравиться