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 ...

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.