Home > Enterprise >  Sending to OutputStream but Read with inputstream read not throwing -1
Sending to OutputStream but Read with inputstream read not throwing -1

Time:01-21

The inputstream reads several bytes but never throws a -1

Here is write:

private void sendData(byte[] data) throws Exception {
  outputStream.write(data);
  outputStream.flush();
...

String txtSend = "$00\r";
sendData(txtSend.getBytes());

Here is the read code:

int i;
char c;
                
while((i = mInputStream.read()) != -1) {
   c = (char)i;
}
System.out.println("it never reaches here.");

It will get stuck in the while loop.
Should I be passing a different character?

.. FYI, this is for serial comm and in minicom, I pass the exact same string and it's able to run fine so idk that last character is the culprit.

CodePudding user response:

Maybe someting like this: Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown. A subclass must provide an implementation of this method. Returns: the next byte of data, or -1 if the end of the stream is reached. Throws: IOException – if an I/O error occurs.

CodePudding user response:

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

https://developer.android.com/reference/java/io/InputStream#read()

As fanyang said, the read function returns a value between 0 and 255, and returning -1 means the end of the stream.

  •  Tags:  
  • Related