一尘不染

用Java读取属性文件

java

我有以下代码尝试读取属性文件:

Properties prop = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();           
InputStream stream = loader.getResourceAsStream("myProp.properties");
prop.load(stream);

我在最后一行有一个例外。特别:

Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at Assignment1.BaseStation.readPropertyFile(BaseStation.java:46)
at Assignment1.BaseStation.main(BaseStation.java:87)

阅读 402

收藏
2020-03-24

共1个答案

一尘不染

根据你的异常,该InputStream值为null,这意味着类加载器未找到你的属性文件。我猜测myProp.properties位于项目的根目录中,如果是这种情况,则需要前面的斜杠:

InputStream stream = loader.getResourceAsStream("/myProp.properties");
2020-03-24