16

I'm making a basic file browser, and want to know how to get the default root directory. I know that java.io.File.listRoots() gives all the roots (for me it's A:\, C:\, D:\, E:\, F:\, G:\, H:\, I:\, L:\ T:\, U:\, X:\, Y:\, Z:\), but I want the one the user uses primarily (i.e. the one with the Operating system on it) so I know from where to start the browsing.

0

2 Answers 2

20

Not sure if this is of any help, but you could try:

import javax.swing.filechooser.*;

FileSystemView.getFileSystemView().getRoots()[0];

or

FileSystemView.getFileSystemView().getHomeDirectory();

or

System.getProperty("user.dir");

For the last snippet, you could get the root directory by navigating upward using getParent() until null is returned.

5
  • @IanGilham I think you meant to comment on another answer
    – Ky -
    Commented Dec 5, 2014 at 16:55
  • 1
    Yes, my bad. You seem to have found the one I meant.
    – Ian Gilham
    Commented Dec 8, 2014 at 10:44
  • String userDir = new File(System.getProperty("user.dir")).getAbsolutePath(); String rootDir = userDir.substring(0, userDir.indexOf(File.separator)+1);
    – CaMiX
    Commented Mar 29, 2016 at 19:25
  • 1
    Downvotes because System.getProperty("user.dir"); does not always return an OS drive path, rather the application's directory. Commented Sep 29, 2017 at 0:13
  • @BullyWiiPlaza is right. Perhaps that was meant to be "user.home"?
    – Ky -
    Commented Sep 29, 2017 at 1:50
10

Getting the operating system root partition is only a thing on Windows since on Unix it's always /.

Hence, the following code works for Windows only:

System.getenv("SystemDrive");

It gets the SystemDrive environment variable value. This should always return the operating system's root partition e.g. C:.

Not the answer you're looking for? Browse other questions tagged or ask your own question.