Getting system root directory in Java

If you are working with file-system in Java, you should understand that your program can run in other types of OS:(Windows, Unix, Linux).
These OS has own file-system structure. For example you need to read or write file in Windows, which located at disk C:\, you should write:

File root = new File("C:\\");
File dir = new File(root, "someDir");
File child = new File(dir, "someFile");

It’s normal, because you know that your file located at disk C:\. Remember – avoid this practice. What if your program will run in Linux? You should modify your code:

File root = new File("/");
File dir = new File(root, "someDir");
File child = new File(dir, "someFile");

It’s not good. Java has great way for getting root directory:

File[] roots = File.listRoots();
File dir = new File(roots[0], "someDir");
File child = new File(dir, "someFile");

I ran this snippet of code in my Windows machine and I got all my local disks. roots[0] is my local disk C:\.

  • Share/Bookmark

Related posts:

  1. Moving file or directory to other directory in Java
  2. Getting working directory in Java
  3. Getting path to user’s home directory in Java
  4. Renaming file or directory in Java
  5. Using OutputStream in Java

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>