Search code examples
javausb

How to list the Connected USB Port Number using Vendor id and product id using java


What is the best API in java to display the connected USB port number using Vendor id and product id?


Solution

  • You can list all serial ports by using simple javax.comm API

    import javax.comm.*;
    import java.util.Enumeration;
    
    public class ListPorts {
    public static void main(String args[]) {
    Enumeration ports = CommPortIdentifier.getPortIdentifiers();
    while (ports.hasMoreElements()) {
    CommPortIdentifier port = (CommPortIdentifier)ports.nextElement();
    String type;
    switch (port.getPortType()) {
    case CommPortIdentifier.PORT_SERIAL:
    type = "Serial"; 
    break;
    default: /// Shouldn't happen
    type = "Unknown"; 
    break;
    }
    System.out.println(port.getName() + ": " + type);
    }
    }
    }
    

    The output would be like

    COM1: Serial
    COM2: Serial
    COM7: Serial
    

    EDIT: Also see a good blog on Creating and using a real-time port monitoring application powered by IBM Lotus.
    Also by using jusb for windows , for linux you can do read and write operation which you want.you will find a a example here