To access files in Java, we are going to need a Path. But what is path, what is a file?
Well it is really simple, lets take and example from real life. You find yourself in your room and you have to get to a living room to take some papers (files). So the path would be YourRoom > Hall > LivingRoom > Papers. The same thing can be used in Java to obtain files from some folder.
1. OS dependent file path notations
There is a difference in Windows and Linux when it comes to writing a Path.
Path written in Windows
Path written in Linux
So the 2 obvious differences are that Windows uses backslashes (\) and file extensions (in this case ".pdf"). In Linux and Mac you use foward slashes (mostly named slash only)..
The Path class is, as its name implies, a programmatic representation of a path in the file system. It includes various methods that can be used to obtain information about the path, access elements of the the path, convert the path to other forms.
Now that we explained what the Path is, we can make an example of how to create one. You can easily create a Path object by using get methods from the Paths, here is an example:
Path p1 = Paths.get("/home/user/file");
Path p2 = Paths.get(args);
Path p3 = Paths.get(URI.create("file:///Users/someone/Testing.java"));
If you are using Linux this code would create:
That is if your home directory is /u/someone
And if you are using Windows it would create:
Of course again assuming that your home directory is C:\someone
Alright, so far we have seen that there are Paths written differently depending on platform you are using. But is there a way to write a Path that will work. There is a way, and it is called Path seperator. Now that we mention one of separators, we will also explain the other, File separator
1.1. Path Separator
Windows and Unix systems have their own path separator (Windows uses semicolon ";" and Unix uses colon ":"). If you want to make cross-platform separator, simply put path.separator. Here is an example:
String pathSeparator = System.getProperty( "path.separator" );
The output will show "user.dir" path, but with your systems path separators
1.2. File separator
Similiar thing as a Path separator but this is for file separation, again Windows and Unix systems have their own File separators (Windows using backslash "\", and Unix using slash "/"). Here is an example of file.separator :
String separator = System.getProperty( "file.separator" );
The output will show "user.dir" with your systems file separators
So in conclusion, in this article, we have explained what are Paths, difference between Windows and Unix system Paths, how to access them, and how to create paths that are are functionable on all platforms. That is all for this article, happy programming