William Wino
William Wino

Reputation: 3829

How to know when to stop InputStream buffering

I communicate with a device through serial port.

I've managed to get the InputStream and read what the device sends.

But the problem is, I simply don't know when to stop reading and proceed to another task.

Here is the simplified code:

inputStream = serialPort.getInputStream();
try
{
    int step = 0;
    while ( (len = inputStream.read(buffer)) > -1 )
    {
        //do something
    }    
    System.out.println("END");
}
catch ( IOException e )
{
    throw new Exception("IO Error");
}

It has never managed to reach the "END". It keeps going on a loop even though the device send nothing. How do I stop the loop when the device stops sending.

Upvotes: 0

Views: 1434

Answers (1)

Mohammod Hossain
Mohammod Hossain

Reputation: 4114

 inputStream = serialPort.getInputStream();
 int available = inputStream .available();

 if (available > 0) {
        byte data[] = new byte[available];
        inputStream .read(data);

   }else{
    logger.info("data is not avilable");
    }

Upvotes: 1

Related Questions