Java InputStream.read(byte[], int, int) method, how to block until the exact number of bytes has been read

前端 未结 4 517
悲&欢浪女
悲&欢浪女 2021-02-04 11:53

I\'m writing a simple client/server network application that sends and receives fixed size messages through a TCP socket.

So far, I\'ve been using the <

相关标签:
4条回答
  • 2021-02-04 12:05

    Use DataInputStream.readFully. Here is JavaDoc

    InputStream in = ...
    DataInputStream dis = new DataInputStream( in );
    byte[] array = ...
    
    dis.readFully( array );
    
    0 讨论(0)
  • 2021-02-04 12:07

    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

    0 讨论(0)
  • 2021-02-04 12:07

    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

    0 讨论(0)
  • 2021-02-04 12:24

    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.

    0 讨论(0)
提交回复
热议问题