找出USB连接的端口

时间:2014-04-02 19:49:44

标签: c# java c++ c usb

我需要一个能够检测插入哪个USB端口闪存驱动器的程序。我可以找到某个驱动器是否连接,但不是它的位置。

例如,当驱动器1连接到USB端口1时,我需要能够说驱动器1连接到端口1.无论如何都要用Java,C#,c ++,c或任何其他语言来实现。我很满意这些语言。

这是我对Java的看法。这告诉我驱动器D或驱动器F何时连接但未连接到哪个端口。提前感谢您的帮助。

public class FindDrive
{

public static void main(String[] args)
{
String[] letters = new String[]{ "A", "B", "C", "D", "E", "F", "G", "H", "I"};
File[] drives = new File[letters.length];
boolean[] isDrive = new boolean[letters.length];

// init the file objects and the initial drive state
for ( int i = 0; i < letters.length; ++i )
    {
    drives[i] = new File(letters[i]+":/");

    isDrive[i] = drives[i].canRead();
    }

 System.out.println("FindDrive: waiting for devices...");

 // loop indefinitely
 while(true)
    {
    // check each drive 
    for ( int i = 0; i < letters.length; ++i )
        {
        boolean pluggedIn = drives[i].canRead();

        // if the state has changed output a message
        if ( pluggedIn != isDrive[i] )
            {
            if ( pluggedIn )
                System.out.println("Drive "+letters[i]+" has been plugged in");
            else
                System.out.println("Drive "+letters[i]+" has been unplugged");

            isDrive[i] = pluggedIn;
            }
        }

    // wait before looping
    try { Thread.sleep(100); }
    catch (InterruptedException e) { /* do nothing */ }

    }
}
}

如果我不够清楚,请告诉我。我真的需要找到解决方案。

1 个答案:

答案 0 :(得分:1)

看起来usb4java可以做你想做的事。查看high-level API,特别是USBDevice#getParentPort()方法。

这里有一些example code让你入门。