import javax.comm.*; public class PortWatcher implements CommPortOwnershipListener { String portName; public PortWatcher(String portName) throws NoSuchPortException { this.portName = portName; CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); portIdentifier.addPortOwnershipListener(this); } public void ownershipChange(int type) { switch (type) { case CommPortOwnershipListener.PORT_OWNED: System.out.println(portName + " has become unavailable"); break; case CommPortOwnershipListener.PORT_UNOWNED: System.out.println(portName + " has become available"); break; case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED: System.out.println("An application has requested onwership of " + portName); break; default: System.out.println("Unknown port ownership event, type " + type); } } public static void main(String[] args) { try { PortWatcher pw = new PortWatcher(args[0]); } catch (Exception e) { System.err.println("Usage: java PortWatcher port_name"); } } }