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.

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

The name argument is a name for the program that wants to use the port and will be returned<br />

by getCurrentOwner() while the port is in use. The timeout argument is the maximum<br />

number of milliseconds this method will block while waiting for the port to become available.<br />

If the operation does not complete within that time, a PortInUseException is thrown.<br />

Example 17.4 is a variation of the PortLister program that attempts to open each unowned<br />

port.<br />

Example 17.4. PortOpener<br />

import javax.comm.*;<br />

import java.util.*;<br />

public class PortOpener {<br />

}<br />

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

}<br />

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

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

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

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

}<br />

switch(com.getPortType()) {<br />

case CommPortIdentifier.PORT_SERIAL:<br />

System.out.print(", a serial port, ");<br />

break;<br />

case CommPortIdentifier.PORT_PARALLEL:<br />

System.out.print(", a parallel port, ");<br />

break;<br />

default:<br />

// important since other types of ports like USB<br />

// and firewire are expected to be added in the future<br />

System.out.print(" , a port of unknown type, ");<br />

break;<br />

}<br />

try {<br />

CommPort thePort = com.open("PortOpener", 10);<br />

System.out.println("is not currently owned.");<br />

thePort.close();<br />

}<br />

catch (PortInUseException e) {<br />

String owner = com.getCurrentOwner();<br />

if (owner == null) owner = "unknown";<br />

System.out.println("is currently owned by " + owner + ".");<br />

}<br />

Here's the output:<br />

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

COM1, a serial port, is not currently owned.<br />

COM2, a serial port, is currently owned by Port currently not owned.<br />

LPT1, a parallel port, is not currently owned.<br />

LPT2, a parallel port, is currently owned by Port currently not owned.<br />

434

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

Saved successfully!

Ooh no, something went wrong!