Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discovering USB Mass Storage Devices with Java

Tags:

java

usb-drive

The story behind...

I really like TV shows but I go back home only twice a month. The rest of the time I live in a house without internet (close to my university though, so free wifi rocks! - when it works - ) so I needed a little software that was able to update my portable hard-disk with my new shows when I go back home where the file server synchronized with podcasts does its job. I did it using Java and it works.

The problem

Right now I have a .properties file where I stored the mounted directory of that usb hd. Not enough. I want the software to be able to discover all of USB mass storage devices and let the user select which one use to store files. How can I do that?

Details

a) it has to be in Java (I mean, It could also work with executing local host commands like dir or something like that)

b) my server is on windows, but I prefer it to be an OS independent solution

like image 723
dierre Avatar asked Sep 30 '10 07:09

dierre


2 Answers

While I didn't see it in your question, I presume you are very familiar with File.listRoots() method which returns an array of well, file roots.

Then, you could just iterate over them, and try to identify if they are flash drives. Some hacks may be like:

File[] roots = File.listRoots();

if (roots == null) {
  // you have a different problem here.  Is it even a computer we are talking about?
}

// Iterate through roots
for (File root : roots) {
    if (root.canWrite()) {  // Or, you could use File.createTempfile with that folder
        // if root does not contain some well know files
        // Or, if root contains some well known files
        // Based on these 2 hacks, or possible other characteristics, you may be reasonably sure
    }
}

That's all I can offer. A lot more can be done with more native programs, and then invoking them from the Java program.

like image 176
Amrinder Arora Avatar answered Oct 02 '22 10:10

Amrinder Arora


You can check the javax.usb project. Currently there are two certified implementations, for Linux and BSD, and a implementation for windows (as it seems, its still not complete, but I supose it allows you to list the USB devices conected).

But I'm not sure if the posibility of listing only USB drives (instead all drives like in @Amrinder Arora answer) worth adopt a new library set and struggle with a semi-complete implementation...

like image 36
Tomas Narros Avatar answered Oct 02 '22 10:10

Tomas Narros