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:
Open the port using the
open()
method ofCommPortIdentifier
. If the port is available, this returns aCommPort
object. Otherwise, aPortInUseException
is thrown.Get the port’s output stream using the
getOutputStream()
method ofCommPort
.Get the port’s input stream using the
getInputStream()
method ofCommPort
.Read and write data onto those streams as desired.
Close the port using the
close()
method ofCommPort
.
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 ...
Get Java I/O now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.