读取config.properties文件时有java.lang.NullPointerException异常,找了很久的原因,但是还是没解决,求解答
config.properties 创建在src目录中 内容如下:name = spirit
pwd = 12345678 import java.io.IOException;
import java.io.InputStream;
import java.util.*;PropertiesTest.java 代码:
public class PropertiesTest {
public static void main(String[] args) {
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("config.properties");
Properties prop = new Properties();
try {
prop.load(is); // 错误指到这里,但是搞不懂是什么原因
} catch (IOException e) {
e.printStackTrace();
String name = prop.getProperty("name");
String pwd = prop.getProperty("pwd");
System.out.println("name:" + name + "pwd" + pwd);
}
}
}
config.properties 创建在src目录中 内容如下:name = spirit
pwd = 12345678 import java.io.IOException;
import java.io.InputStream;
import java.util.*;PropertiesTest.java 代码:
public class PropertiesTest {
public static void main(String[] args) {
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("config.properties");
Properties prop = new Properties();
try {
prop.load(is); // 错误指到这里,但是搞不懂是什么原因
} catch (IOException e) {
e.printStackTrace();
String name = prop.getProperty("name");
String pwd = prop.getProperty("pwd");
System.out.println("name:" + name + "pwd" + pwd);
}
}
}
解决方案 »
- ClassLoader实现类似tomcat功能 问题!!!
- 运行时的出错,t java.lang.ClassLoader.defineClass1(Native Method)
- 如何分离变量和运算符?
- 请问:inner class中使用的参数为什么必须为final啊?
- 一个死锁难题!能者入!
- 在线等!!急!!关于Timestamp 与 Long 的转换的问题!
- (在线请教)请问如何判断字符串中的空格和标点?(急急急!!)
- 怎么设置编码问题?
- 应聘中间件开发人员时碰到的两到面试题!!!
- 关于classloader的一个问题
- 响应键盘事件
- struts2拦截器返回到input指定的页面,原先填写的内容没了怎么办?
.getResourceAsStream("config.properties")修改为 :InputStream is = PropertiesTest.class.getClassLoader()
.getResourceAsStream("config.properties")
2.NullPointerException是因为找不到文件。因为getResourceAsStream默认则是从ClassPath根下获取,path不能以’/'开头,最终是由ClassLoader获取资源。所以你这表示的要找的文件是在当前的.class(字节码文件)所在目录下。你不是把config.properties放在src下了么,放在bin下面就可以了。import java.io.IOException;
import java.io.InputStream;
import java.util.*;public class PropertiesTest {
public static void main(String[] args) {
InputStream is = PropertiesTest.class.getClassLoader()
.getResourceAsStream("config.properties");
Properties prop = new Properties();
try {
prop.load(is); // 错误指到这里,但是搞不懂是什么原因
String name = prop.getProperty("name");
String pwd = prop.getProperty("pwd");
System.out.println("name:" + name + "pwd" + pwd);
} catch (IOException e) {
e.printStackTrace();
}
}
}