Java InputStream.read(byte[], int, int) method, how to block until the exact number of bytes has been read
I'm writing a simple client/server network application that sends and receives fixed size message开发者_如何学编程s through a TCP socket.
So far, I've been using the getInputStream()
and getOutputStream()
methods of the Socket
class to get the streams and then call the read(byte[] b, int off, int len)
method of the InputStream
class to read 60 bytes each time (which is the size of a message).
Later on, I read the Javadoc for that method:
public int read(byte[] b, int off, int len) throws IOException
Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer.
I was wondering if there's any Java "out-of-the-box" solution to block until len bytes have been read, waiting forever if necessary.
I can obviously create a simple loop but I feel like I'm reinventing the wheel. Can you suggest me a clean and Java-aware solution?
Use DataInputStream.readFully
. Its Javadocs directs the reader to the DataInput
Javadocs Javadocs, which state:
Reads some bytes from an input stream and stores them into the buffer array
b
. The number of bytes read is equal to the length ofb
.
InputStream in = ...
DataInputStream dis = new DataInputStream( in );
byte[] array = ...
dis.readFully( array );
The simple loop is the way to go. Given the very small number of bytes you're exchanging, I guess it will need just one iteration to read everything, but if you want to make it correct, you have to loop.
a simple for one-liner will do the trick
int toread = 60;
byte[] buff;
for(int index=0;index<toread;index+=in.read(buff,index,toread-index));
but most of the time the only reason less bytes would be read is when the stream ends or the bytes haven't all been flushed on the other side
I think the correct version of ratchet freak's answer is this :
for (int index = 0; index < toRead && (read = inputStream.read(bytes, index, toRead-index))>0 ; index+= read);
it stops reading if read returns -1
精彩评论