Friday, December 16, 2011

Java - getClass().getClassLoader().getResource("myfolder/data/file.txt").getPath();

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();



This code will try to get exact path of foldermyfolder/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.)



1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai java 8 online training JavaEE Training in Chennai Java EE Training in Chennai