Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

sockets - how to count Usb port using java?

I want to detect list of USB Ports which are free (not occupied) in system to while I checked with CommPortIdentifier.getPortIdentifiers() while this returns me Enumeration with 0 elements I'd add librxtxcomm.jar too in classpath.

This should return each Port detail

Enumeration pList = CommPortIdentifier.getPortIdentifiers(); 
System.out.println(pList.hasMoreElements());

this returns 0 mean no List/Enumeration.

Rest Code :

public class CommPortLister{

    /** Simple test program. */
    public static void main(String[] ap) {
        new CommPortLister().list();
    }

    /** Ask the Java Communications API * what ports it thinks it has. */
    protected void list() {
        // get list of ports available on this particular computer, by calling static method in CommPortIdentifier.

        System.out.println("");
        Enumeration pList = CommPortIdentifier.getPortIdentifiers();
        System.out.println("Before While");
        // CommPortIdentifier.getPortIdentifiers(); 
        // Process the list.
        System.out.println(pList.hasMoreElements());

        while (pList.hasMoreElements()) {
            System.out.println("While Loop");
            CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();
            System.out.print("Port " + cpi.getName() + " ");
            if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println("is a Serial Port: " + cpi);
            } else if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL)  {
                System.out.println("is a Parallel Port: " + cpi);
            } else  {
                System.out.println("is an Unknown Port: " + cpi);
            }
        }
        System.out.println("After While");
    }
}

Code to detect USB port while i am unable to detect USB Port

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Please try using ServerSocket(portNo). If there is an service running in the port, it will error so catch the exception and try the next port.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...