我要获取Properties中Key的值。
public class PropertiesInfo {
private static Properties cache = new Properties();
static {
try {
cache.load(PropertiesInfo.class.getClassLoader().getResourceAsStream("merchantInfo.properties"));
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取指定key的值
* @param key
* @return
*/
public static String getValue(String key) {
return cache.getProperty(key);
}
我在自己写了个Test类
String value = PropertiesInfo.getValue("p1_MerId");
System.out.print(value);
可以正确打印出结果。
但当写入Servlet的DoPost(。。。)方法中时,报Servlet.service() for servlet PaymentRequest threw exception
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:365)
at java.util.Properties.load(Properties.java:293)
不知道到底哪里出错了啊??
这个问题很常见,需要注意的是properties文件加载的位置。你的properties需要跟.class文件放在一起。
最好的方法我可以参考这个例子:
public class PropReader {
public static Properties getProperties(String file){
Class o = getCallerClass();
InputStream ins = o.getResourceAsStream(file);
Properties props = new Properties();
try {
props.load(ins);
} catch (IOException e) {
e.printStackTrace();
}finally{
try{ins.close();}catch(Exception e){}
}
return props;
}
public static Class getCallerClass(){
StackTraceElement[] stack =
(new Throwable()).getStackTrace();
Class o = null;
try {
o = Class.forName(stack[2].getClassName());
} catch (ClassNotFoundException e) {
System.err.println(e.getMessage());
}
return o;
}
}
这个静态类的getProperties方法需要一个文件名,这个properties文件需要跟使用properties的类文件放在同一个目录下即可。然后就不用考虑servlet的路径问题了。
前提是你这段
[code="java"]
private static Properties cache = new Properties();
static {
try {
cache.load(PropertiesInfo.class.getClassLoader().getResourceAsStream("merchantInfo.properties"));
}catch (Exception e) {
e.printStackTrace();
}
}[/code]
要在servlet dopost之前先运行
没找到merchantInfo.properties文件吧,自己调试下,在servlet调用PropertiesInfo 的方法的地方打断点,看有没执行到cache.load(PropertiesInfo.class.getClassLoader().getResourceAsStream("merchantInfo.properties"));
servlet是多线程的情况,你自己写的一个类只是单线程,多线程可能出问题