Different behavior of ClassLoader.getSystemClassLoader (). GetResource () in Servlet Container and Test Environment

I have a web application, my requirement is to read some files and process them and store the file content in the 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.



folder / directory is available in the classpath. When MyUtil.readFiles()

called in a JUnit test case, it works fine. But when he called the method servelet.init()


it gave null.


source to share

1 answer

You can getClass().getClassLoader().getResource(...)

alternatively useClassLoader.getSystemClassLoader().getResource(...)

The alternative works because there is more than one classloader in the web server and you cannot be sure which one loaded your class. I am assuming the ClassLoader

class is loaded before anything with the default java classloader and then the class MyUtil

is loaded using another classloader with the webserver hence it resulted in a different classpath.



All Articles