读取properties文件

//继承了 ServletContextListener
public void contextInitialized(ServletContextEvent sce) {
try {
p.load(ClassLoader.getSystemResourceAsStream("config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
driver = p.getProperty("database.driver");
url = p.getProperty("database.url");
user = p.getProperty("database.user");
pass = p.getProperty("database.pwd");
}

我在web.xml配置一个监听,当服务启动时就加载“config.properties”文件,但是在加载的时候报空指针异常,错误行就是p.load()这一行,我不知道为什么会报这样的异常,怎么做才能正确的加载文件。

在main是可以加载到配置文件的,但是如果是发布在服务器上,配置文件会被部署到classpath下,所以加载不到。
试试这个把:
String str = Thread.currentThread().getContextClassLoader().getResource("config.properties").getPath();
p.load(new FileInputStream(str));

p.load(ClassLoader.getSystemResourceAsStream("config.properties")); 路径不正确,p应该为空了

加载的路径不对。web容器下的path问题,详细说明可以上网搜索Tcomat path路径。

p.load(类名.class.getClassLoader().getResourceAsStream("config.properties"));

好吧 。。。 我看不下去了
ResourceBundle CONNECT_RESOURCE = ResourceBundle.getBundle("config");
String db = CONNECT_RESOURCE.getString("DB")