Debugging classpath issues

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s