file.listRoots not working for a portable USB drive in Java

341 views Asked by At

file.listRoots() works fine for internal file drive information, but is not getting USB and portable file info. Here is my code:

File[] paths; 
try {
    // returns pathnames for files and directory
    paths = File.listRoots();
    for (File path : paths) // for each pathname in pathname array
        System.out.println(path); // prints file and directory paths
} catch(Exception e) { // if any error occurs
    e.printStackTrace();
}

I don't understand why does my portable USB info not fetch?

1

There are 1 answers

5
DuncG On

If your USB drive is connected and is accessible, you could check whether NIO code shows the volumes as follows:

for (Path root : FileSystems.getDefault().getRootDirectories()) {
    FileStore fs = Files.getFileStore(root);
    System.out.format("FileStore %s\tName: '%s'\tType: %s%n", root, fs.name(), fs.type());
    System.out.println();
}

Inside above loop you can also check other filesystem attributes such as removable storage flag:

String[] attrs = new String[]{"volume:isRemovable"};

for (String s : attrs) {
    System.out.format("\t%s=%s", s, fs.getAttribute(s));
}