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.

CommPortOwnershipListener.PORT_OWNED<br />

CommPortOwnershipListener.PORT_UNOWNED<br />

CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED<br />

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

PORT_OWNED means some application has taken ownership of the port. PORT_UNOWNED means<br />

some application has released ownership of the port. Finally, PORT_OWNERSHIP_REQUESTED<br />

means some application has requested ownership of the port but does not yet have it, because<br />

another application owns it. If the owner of the port hears the event, it can close the port to<br />

give it up to the requesting application. Example 17.5 is a program that watches for port<br />

ownership changes. It's of limited use, since these events only appear to be fired when a <strong>Java</strong><br />

program takes over or releases a port, not when other programs do.<br />

Example 17.5. PortWatcher<br />

import javax.comm.*;<br />

public class PortWatcher implements CommPortOwnershipListener {<br />

String portName;<br />

public PortWatcher(String portName) throws NoSuchPortException {<br />

this.portName = portName;<br />

CommPortIdentifier portIdentifier =<br />

CommPortIdentifier.getPortIdentifier(portName);<br />

portIdentifier.addPortOwnershipListener(this);<br />

}<br />

public void ownershipChange(int type) {<br />

}<br />

}<br />

}<br />

switch (type) {<br />

}<br />

case CommPortOwnershipListener.PORT_OWNED:<br />

System.out.println(portName + " has become unavailable");<br />

break;<br />

case CommPortOwnershipListener.PORT_UNOWNED:<br />

System.out.println(portName + " has become available");<br />

break;<br />

case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:<br />

System.out.println("An application has requested onwership of "<br />

+ portName);<br />

break;<br />

default:<br />

System.out.println("Unknown port ownership event, type " + type);<br />

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

try {<br />

PortWatcher pw = new PortWatcher(args[0]);<br />

}<br />

catch (Exception e) {<br />

System.err.println("Usage: java PortWatcher port_name");<br />

}<br />

436

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

Saved successfully!

Ooh no, something went wrong!