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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

javax.comm.CommPortIdentifier@be4c9581<br />

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

This shows you that my system has four ports, though it doesn't tell you what those ports are.<br />

Of course, the output will vary depending on how many serial and parallel ports your system<br />

possesses, and those first few lines are liable to disappear in the release version of the Comm<br />

API. Clearly, a better toString() method is needed. (CommPortIdentifier merely inherits<br />

java.lang.Object's toString() method.) You'll see how to work around this in the next<br />

section.<br />

You can also get a CommPortIdentifier by using the static method getPortIdentifier()<br />

to request a port identifier, either by name or by the actual port object. The latter assumes that<br />

you already have a reference to the relevant port, which usually isn't the case. The former<br />

allows you to choose from Windows standard names like "COM1" and "LPT2" or Unix<br />

names like "Serial A" and "Serial B." The exact format of a name is highly platform- and<br />

implementation-dependent. If you ask for a port that doesn't exist, a NoSuchPortException is<br />

thrown. Example 17.2 looks for serial and parallel ports by starting with COM1 and LPT1 and<br />

counting up until one is missing. Be warned that this code is highly platform-dependent and<br />

probably won't work on Unix or the Mac.<br />

Example 17.2. NamedPortLister<br />

import javax.comm.*;<br />

public class NamedPortLister {<br />

}<br />

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

}<br />

// List serial (COM) ports.<br />

try {<br />

int portNumber = 1;<br />

while (true) {<br />

CommPortIdentifier.getPortIdentifier("COM" + portNumber);<br />

System.out.println("COM" + portNumber);<br />

portNumber++;<br />

}<br />

}<br />

catch (NoSuchPortException e) {<br />

// Break out of loop.<br />

}<br />

// List parallel (LPT) ports.<br />

try {<br />

int portNumber = 1;<br />

while (true) {<br />

CommPortIdentifier.getPortIdentifier("LPT" + portNumber);<br />

System.out.println("LPT" + portNumber);<br />

portNumber++;<br />

}<br />

}<br />

catch (NoSuchPortException e) {<br />

// Break out of loop.<br />

}<br />

Once again, here's the output from a stock Wintel box:<br />

431

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

Saved successfully!

Ooh no, something went wrong!