DataInputStream.read () vs DataInputStream.readFully ()

Im creating a simple TCP / IP socket application

What is different from this:

DataInputStream in = new DataInputStream(clientSocket.getInputStream()); byte[] buffer = new byte[100]; in.readFully(buffer); 

Against this:

 DataInputStream in = new DataInputStream(clientSocket.getInputStream()); byte[] buffer = new byte[100]; in.read(buffer); 

I looked at the documentation, they have the exact same description. readFully() and read() So, can I assume it is the same?

+5
source share
2 answers

The Javadoc for DataInput.readFully(byte[] b) states:

Reads a few bytes from the input stream and saves them to buffer array b . The number of bytes read is equal to the length b .

The Javadoc for DataInputStream.read(byte[] b) states:

Reads a certain number of bytes from the contained input stream and stores them in buffer array b . The number of bytes actually read is returned as an integer. This method is blocked until the input is accessible, the end of the file, or an exception is thrown .

Basically, readFully() will read exactly b.length bytes, while read() will read up to b.length , maybe less, regardless of what is available from the input stream.

+9
source

Using read , you need to check the return value to see how many bytes are actually read.

 byte[] buffer = new byte[100]; if (in.read(buffer) < 100){ // fail } 

instead of readFully , an IOException will be thrown , if 100 bytes cannot be read, there is no need to check the return value, simplify the bit.

0
source

Source: https://habr.com/ru/post/1202800/


All Articles