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.)
ReplyDeleteAwesome..You have clearly explained …Its very useful for me to know about new things..Keep on blogging..
Superb blog and great post.Its truly supportive for me, anticipating for all the more new post. Continue Blogging!
artificial intelligence internship | best final year projects for cse | internship certificate online | internship for mba finance students | internship meaning in tamil