Search code examples
javaarduino-unoioexceptionserial-communication

java.io.IOException: Underlying input stream returned zero bytes


I'm trying to read arduino uno data using a java program with the help of rxtx library. I'm using COM8 serial communication port for this. I'm using win10.

my problem: when i'm using 'serial.print', then down java function working fine and retrieving everything that arduino sending. But when i try to use 'serial.write' in arduino then an ioexception occurs "java.io.IOException: Underlying input stream returned zero bytes" I dont know why. my need is to use 'serial.write' method, please tell me what is wrong in code. both codes is down

Java Function code:

public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine=input.readLine();
                System.out.println(inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

arduino uno code:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(9, 10);
void setup() {
    mySerial.begin(9600); // Setting the baud rate of Software Serial Library  
    Serial.begin(9600);  //Setting the baud rate of Serial Monitor 
}
void loop() {
    if(mySerial.available() > 0) {
         Serial.print(mySerial.read());
    }
}

Solution

  • I was using serial.println which breaks the line in the end, while serial.write doesn't. On the other side the readLine() method of java reads the entire line, until it recorgnizes a line break.(\n)

    problem: in case of serial.write(), there is no line break "\n", so readLine() is unable to find any line at all and results in java.io.IOException: Underlying input stream returned zero bytes atleasst one line break is required for readLine() to work.

    solution: while using serial.write() manually provide line break statement("\n")