Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

java - 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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...