There’s nothing more frustrating than wasting time figuring out why some resources (e.g. configuration files for log4j, hibernate…) are not loaded correctly from the classpath.
The few lines of code below help narrow down these kind of issues. Knowing what’s the classpath at runtime and being able to test if it covers a specific file is half the battle won already.
1- Print out name of all files on the classpath
String classpath = java.lang.System.getProperty( "java.class.path" );
for (String path : classpath.split(System.getProperty("path.separator"))){
File f = new File (path);
String resource = (f.isDirectory()?Arrays.asList( f.list()).toString():f.toString());
System.out.println (resource);
}
2- Check wether a specific file is on the classpath
String myResource = .... ; InputStream is = getClass().getResourceAsStream(myResource); System.out.println (myResource + " is " + (is==null?"not":"") + " on the classpath");
Advertisement