读取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);
}
}
}
解决方案 »
- ResultSet的问题纠结,来讨论下
- 点击JInternalFrame打开另一个JInternalFrame
- 如何修改fillrect和clearrect在快速拖动的时候出现间断的问题?
- 谁来帮我讲解一下这道题~~~谢谢
- 为什么com.microsoft.jdbc.sqlserver.SQLServerDriver不能成功连接数据库,而用sun.jdbc.odbc.JdbcOdbcDriver却没有问题?
- 请问如何获得自身程序所在的目录???
- 请问这个程序哪出错了?运行不起来唉
- Double到String
- Linux下的"compress"是用什么压缩法的,java有没有提供解压的类?
- 在JAVA程序中如何调用DLL库
- 响应键盘事件
- 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();
}
}
}