// Main.javapackagecom.github.mccxj.test;publicclassMain{publicstaticvoidmain(String[]args){newTestServlet().test();}}// TestServlet.Javapackagecom.github.mccxj.test;publicclassTestServlet{publicvoidtest(){InputStreamis=TestServlet.class.getClassLoader().getResourceAsStream("config.properties");if(is==null){thrownewRuntimeException("couId not found config.properties");}}}
假设目录结构是这样的,其中jar下面的表示是在jar包里边的内容:
1234567
test -lib
-test.jar
-com/github/mccxj/test/Main.class
-main.jar
-com/github/mccxj/test/TestServlet.class
-config.properties
// TestServlet.Java
package com.github.mccxj.test;
public class TestServlet {
public void test() {
- InputStream is = TestServlet.class.getClassLoader().getResourceAsStream("config.properties");+ InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"); if(is == null){
throw new RuntimeException("couId not found config.properties");
}
}
}
把目录结构恢复成:
1234567
test -lib
-test.jar
-com/github/mccxj/test/Main.class
-main.jar
-com/github/mccxj/test/TestServlet.class
-config.properties