The following example shows how to load resources from classpath.
Java provides the following APIs to get the class path resource as URL or Stream.
java.lang.Class public URL getResource(String paramString)
public InputStream getResourceAsStream(String paramString)
java.lang.ClassLoader public URL getResource(String paramString)
public InputStream getResourceAsStream(String paramString)
public Enumeration<URL> getResources(String paramString)
/**
* Access the file in the same directory as class
* Ex: <PWD>/com/bethecoder/tutorials/core/gen/local_prop.txt
*/
String fileToSearch = "local_prop.txt";
URL fileURL = LoadClassPathResource.class.getResource(fileToSearch);
System.out.println("");
System.out.println("Resource '" + fileToSearch + "' is found at : " + fileURL);
System.out.println("");
/**
* Access the file in the root directory of class
* Ex: <PWD>/top_level_prop.txt
*/
fileToSearch = "top_level_prop.txt";
fileURL = LoadClassPathResource.class.getClassLoader().getResource(fileToSearch);
System.out.println("Resource '" + fileToSearch + "' is found at : " + fileURL);
System.out.println("");
/**
* Load resource from application class path
*/ try {
Enumeration<URL> urls = ClassLoader.getSystemResources(fileToSearch); if (urls.hasMoreElements()) {
System.out.println("Resource '" + fileToSearch + "' is found in system resources");
} else {
System.out.println("Resource '" + fileToSearch + "' is not found in system resources");
}
System.out.println();
while (urls.hasMoreElements()) {
System.out.println("Resource '" + fileToSearch + "' is found in system resources at : " + urls.nextElement());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Execute the commands shown below and observe the output,
LoadClassPathResource.class.getResource() can access resources relative to the directory of current class.
LoadClassPathResource.class.getClassLoader().getResource() can access resources relative to the root directory of class.
ClassLoader.getSystemResources() can access the resources from system class path.
The order of resources returned by this API depends on the order of classpath entries.
Make a JAR out of LoadClassPathResource.class and property files. Execute the commands shown below and observe the output,