Skip to content

Java InputStream and OutputStream Interfacing Usage Example

Will Hedgecock edited this page Mar 12, 2015 · 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, 100, 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 will decrease CPU load as it will rely on the operating system to block until a value is received.