Access resource / file packaged inside a jar or a located on classpath. Two ways to access the file located inside jar or located on classpath.
- Use
getResourceAsStream("filename")
on ClassLoader, one can retrieve the class loader instance from class instance of any class orThread.currentThread().getClassLoader()
. When you try to load the file using class loader, file will be always searched inside root folder on classpath. e.g.Thread.currentThread().getClassLoader().getResourceAsStream("config.properties")
andThread.currentThread().getClassLoader().getResourceAsStream("/config.properties")
either way class loader will try to search file from root folder which is on class path or from root folder inside jar. - Use
getResourceAsStream("filename")
on Class instance of a class. One can retrieve theclass
instance usingClassName.class
orthis.getClass()
. When you try to load the file using class, file search will depend on how do you specify the file name. When you specify fileconfig.properties
this.getClass().getResourceAsStream("config.properties")
, file will be searched inside same package as that of given class on which you are callinggetResourceAsStream()
. When you specify file like/config.properties
given file will be searched from root folder which is on class path or from root folder inside jar.
Access resource / file from file location
To access file form given path outside the class path, one need to make use of java.io.File
File file = new File(“filename with absolute path”);
FileInputStream fStream = new FileInputStream(file);
See also
- Install ZeroMQ on ubuntu with Java Binding
- Compare more than two war files and repackage them excluding common jars
- Tomcat 7 onwards set additional JAVA_OPTS options
- Jersey REST retrieve List of custom object
- Generate complete package (ZIP) of Java (executable jar) application with required dependencies in it using Maven