`import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Emaldome4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
InputStream is = context.getResourceAsStream("/res/config.properties");
Properties props = new Properties();
props.load(is);
System.out.println(props.getProperty("email"));
}
}`
访问:
http://localhost:8080/day04/Emaldome4
结果:
类加载器只能加载IDE工具下src目录下的资源文件,其它目录无法加载
此时/表示:/WEB-INF/classes/目录
//通过类加载器加载src/config.properteis资源文件
//取得当前对象的字节码对象
Class clazz = this.getClass();
//取得当前对象的类加载器
ClassLoader cl = clazz.getClassLoader();
//
InputStream is = cl.getResourceAsStream("/cn/config/config.properties");
Properties props = new Properties();
props.load(is);
System.out.println(props.getProperty("email"));
原文地址:http://blog.51cto.com/357712148/2104563