InputStream misses byte while reading in a loop

326 views Asked by At

I'm trying to write a java program to read from a COM port. There are 266 bytes to read, and since the 266 bytes are not generated all together, which means that the input stream can be empty at sometime, I used a while loop to read all 266 bytes. The problem is that SOMETIMES one byte may be missed (only one byte), according to my checking the received bytes one by one. Here are the codes:

While(numOfBytes < 266) {
    if(!(inputStream.available() > 0)) continue;
    inputStream.read(buffer);
    data[numOfBytes] = buffer[0];
    numOfBytes++;
}
2

There are 2 answers

1
NameSpace On

You give input stream an array to store data in (is.read(buffer)), but regardless of how much it reads, storing only 1 byte, and incrementing number of bytes by 1.

Try instead something like:

    While(numOfBytes < 266) {
        if(!(inputStream.available() > 0)) continue;
        int b = inputStream.read();

        if(b >= 0){
            data[numOfBytes] = (byte) b ;
            numOfBytes++;
        }
    }       
0
Scary Wombat On

normally I would do it like this

 byte[] in = new byte[4196];
 int bytesRead = 0;
 while ((bytesRead = is.read(in)) != -1) {
     // add to a StringBuffer maybe
 }