1

I wonder how can I get a current volume using Java?

For example:

C:\ or D:\ or on Unix.

JohnWinter
  • 1,003
  • 5
  • 12
  • 25
  • 2
    [`File.listRoots()`](https://docs.oracle.com/javase/8/docs/api/java/io/File.html#listRoots--) and `System.getProperty("user.dir");` – jmj Jun 09 '15 at 20:08
  • I would get the current working directory as an absolute path and extract the filesystem from it. Some tips for getting the current working diretory as an absolute path using Java are at http://stackoverflow.com/questions/4871051/getting-the-current-working-directory-in-java. –  Jun 09 '15 at 20:18

2 Answers2

2

Use either:

File currDir = new File(".");

or as @JigarJoshi, more or less, stated:

File currDir = new File(System.getProperty("user.dir", "."));

which defaults to the first solution when the property is not set.

To obtain the root volume:

Path root = currDir.toPath().getRoot();
0

Try this:

String currentPath = new File(".").getAbsoluteFile().toString();
for (File f : File.listRoots()) {
    if (currentPath.startsWith(f.toString())) {
        System.out.println(f);
    }            
}
Pavel Němec
  • 272
  • 1
  • 5
  • 16