O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Communicating with a Device on a Port

The open() method of the CommPortIdentifier class returns a CommPort object. The javax.comm.CommPort class has methods for getting input and output streams from a port and for closing the port. There are also a number of driver-dependent methods for adjusting the properties of the port.

Communicating with a Port

There are five basic steps to communicating with a port:

  1. Open the port using the open() method of CommPortIdentifier. If the port is available, this returns a CommPort object. Otherwise, a PortInUseException is thrown.

  2. Get the port’s output stream using the getOutputStream() method of CommPort.

  3. Get the port’s input stream using the getInputStream() method of CommPort.

  4. Read and write data onto those streams as desired.

  5. Close the port using the close() method of CommPort.

Steps 2 through 4 are new. However, they’re not particularly complex. Once the connection has been established, you simply use the normal methods of any input or output stream to read and write data. The getInputStream() and getOutputStream() methods of CommPort are similar to the methods of the same name in the java.net.URL class. The primary difference is that with Comm ports, you’re completely responsible for understanding and handling the data that’s sent to you. There are no content or protocol handlers that perform any manipulation of the data. If the device attached to the port requires a complicated protocol—for example, a fax modem—then you’ll have to handle the protocol ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required