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

Identifying Ports

The javax.comm.CommPortIdentifier class is the control room for the ports on a system. It has methods that list the available ports, figure out which program owns them, take control of a port, and open a port so you can perform I/O with it. The actual I/O, stream-based or otherwise, is performed through an instance of javax.comm.CommPort that represents the port in question. The purpose of CommPortIdentifier is to mediate between different programs, objects, or threads that want to use the same port.

Finding the Ports

Before you can use a port, you need a port identifier for the port. Because the possible port identifiers are closely tied to the physical ports on the system, you cannot simply construct an arbitrary CommPortIdentifier object. (For instance, Macs have no parallel ports, and iMacs don’t have serial or parallel ports.) Instead, you use one of several static methods in javax.comm.CommPortIdentifier that use native methods and nonpublic constructors to find and create the right port. These include:

public static Enumeration getPortIdentifiers()
public static CommPortIdentifier getPortIdentifier(String portName) 
              throws NoSuchPortException
public static CommPortIdentifier getPortIdentifier(CommPort port) 
              throws NoSuchPortException

The most general of these is CommPortIdentifier.getPortIdentifiers(), which returns a java.util.Enumeration containing one CommPortIdentifier for each of the ports on the system. Example 17.1 uses this method to list all the ports ...

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