Harish Rawal
Harish Rawal

Reputation: 236

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

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?

Upvotes: 0

Views: 373

Answers (1)

DuncG
DuncG

Reputation: 15196

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));
}

Upvotes: 2

Related Questions