cartonwang 2009-06-10 19:58
浏览 205
已采纳

奇怪,Properties问题。我在Test类中可用,怎么一写到Servlet中就报空指针

我要获取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)

不知道到底哪里出错了啊??

  • 写回答

3条回答 默认 最新

  • iteye_8220 2009-06-10 22:43
    关注

    这个问题很常见,需要注意的是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的路径问题了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line