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

No related posts.

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>

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna,tincidunt vitae molestie nec,molestie at mi. Nulla nulla lorem,suscipit in posuere in,interdum non magna.