23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

D:\JAVA\16>java NamedPortLister<br />

COM1<br />

COM2<br />

LPT1<br />

LPT2<br />

<strong>Java</strong> I/O<br />

Now you can see that I have two serial and two parallel ports. However, this same program<br />

would fail on Unix, because it relies on hard-wired port names.<br />

17.2.2 Getting Information About a Port<br />

Once you have a CommPortIdentifier identifying a particular port, you can discover<br />

information about the port by calling several accessor methods. These include:<br />

public String getName()<br />

public int getPortType()<br />

public String getCurrentOwner()<br />

public boolean isCurrentlyOwned()<br />

The getName() method returns the platform-dependent name of the port, such as "COM1"<br />

(Windows) "Serial A" (Solaris) or "modem" (Mac). [1] The getPortType() method returns one<br />

of the two mnemonic constants CommPortIdentifier.PORT_SERIAL or<br />

CommPortIdentifier.PORT_PARALLEL:<br />

public static final int PORT_SERIAL = 1;<br />

public static final int PORT_PARALLEL = 2;<br />

The isCurrentlyOwned() method returns true if some process, thread, or application<br />

currently has control of the port. It returns false otherwise. If a port is owned by another <strong>Java</strong><br />

program, the getCurrentOwner() returns the name supplied by the program that owns it;<br />

otherwise, it returns null. This isn't too useful, because it doesn't handle the much more likely<br />

case that a non-<strong>Java</strong> program like Dial-Up Networking or PPP is using the port. A comment<br />

in the source code indicates that this should be fixed so that non-<strong>Java</strong> programs can also be<br />

identified; this limitation may not exist by the time you read this. Example 17.3 is a revision<br />

of the PortLister in Example 17.1 that uses these four accessor methods to provide<br />

information about each port rather than relying on the inherited toString() method.<br />

Example 17.3. PrettyPortLister<br />

import javax.comm.*;<br />

import java.util.*;<br />

public class PrettyPortLister {<br />

public static void main(String[] args) {<br />

Enumeration e = CommPortIdentifier.getPortIdentifiers();<br />

while (e.hasMoreElements()) {<br />

CommPortIdentifier com = (CommPortIdentifier) e.nextElement();<br />

System.out.print(com.getName());<br />

1 That last one is hypothetical. The Comm API hasn't been ported to the Mac as of the time of this writing.<br />

432

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!