Java - getClass().getClassLoader().getResource("myfolder/data/file.txt").getPath();
A relatively simple concept that confuses many java beginners!
Java Code:
String path = getClass().getClassLoader().getResource("myfolder/data/file.txt").getPath();
Means:
This code will try to get exact path of folder “myfolder/data/file.txt”.
The parent folder of this folder “myfolder/data/file.txt” should be mentioned in class path.
e.g. If the exact path of this folder is “C:/properties/myfolder/data/file.txt”; path “C:/properties” should be mentioned in classpath of the application (build-path in eclipse). When the above mentioned code is executed in application, it returns the exact path of the folder location and assigns it to ‘path’ variable.
Hence after execution of this code, ‘path’ variable will contain value “C:/properties/myfolder/data/file.txt”.
If we change root location of the application or we change folder structure of the parent folder of “myfolder/data/file.txt“, we will need to change only classpath.
This avoids hard-coding of the absolute path in source code. (Important for portability of application across windows and unix platforms.)