I have a web application my requirement is to read some files and process it and persist the file content in database when the application starts.
class MyUtil{
/**
*Read the files
*/
public static void readFiles(){
File file = new File(ClassLoader.getSystemClassLoader().getResource("MyFile").toURI()); //NullPointerException
// ClassLoader.getSystemClassLoader().getResource("MyFile") is giving null in servlet.init() method.
if (file.isDirectory()) {
//Read all the files and persist.
}
}
}
MyFile folder/dir is available in class path. When MyUtil.readFiles() is called in JUnit test case it works fine. But when It's called in servelet.init() method ClassLoader.getSystemClassLoader().getResource("MyFile") gives the null.
You can use getClass().getClassLoader().getResource(...) as an alternative to ClassLoader.getSystemClassLoader().getResource(...)
The alternative works because in webserver there are more than one class loader, and you can't be sure whichone loaded your class. I guess ClassLoader class loaded before anything with default java class loader, and then MyUtil class loaded with different class loader with the webserver hence it resulted in different classpath.
来源:https://stackoverflow.com/questions/25869884/different-behavior-of-classloader-getsystemclassloader-getresource-in-servle