日期:2014-05-20  浏览次数:20921 次

读取config.properties文件时有异常
读取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);
}
}
}




------解决方案--------------------
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("config.properties")

修改为 :

InputStream is = PropertiesTest.class.getClassLoader()
.getResourceAsStream("config.properties")
------解决方案--------------------
两个原因:1.打印输出不能放在catch块里,否则有异常才能输出你要取得值;
2.NullPointerException是因为找不到文件。因为getResourceAsStream默认则是从ClassPath根下获取,path不能以’/'开头,最终是由ClassLoader获取资源。所以你这表示的要找的文件是在当前的.class(字节码文件)所在目录下。你不是把config.properties放在src下了么,放在bin下面就可以了。
Java code

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();            
        }
    }
}