Skip to content

Java InputStream and OutputStream Interfacing Usage Example

Will Hedgecock edited this page Jan 10, 2019 · 9 revisions

If you prefer to use the standardized Java InputStream/OutputStream interfaces to interact with the serial port, you can do so by requesting these interfaces directly from the SerialPort object as follows:

SerialPort comPort = SerialPort.getCommPorts()[0];
comPort.openPort();
comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
InputStream in = comPort.getInputStream();
try
{
   for (int j = 0; j < 1000; ++j)
      System.out.print((char)in.read());
   in.close();
} catch (Exception e) { e.printStackTrace(); }
comPort.closePort();

Note: The call to setComPortTimeouts() is unnecessary as the library will function correctly without it; however, setting a semi-blocking read timeout with a value of 0 will ensure that no SerialPortTimeoutExceptions are thrown.