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:\.
Related posts:

Recent Comments