用Java读取属性文件

用Java读取属性文件

本文介绍了用Java读取属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code trying to read a properties file:

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

我在最后一行得到一个例外。具体来说:

I get an exception at the last line. Specifically:

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)

谢谢,
Nikos

thanks,Nikos

推荐答案

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

Based on your exception, the InputStream is null, this means the class loader is not finding your properties file. I'm guessing that myProp.properties is in the root of your project, if that's the case, you need a preceding slash:

InputStream stream = loader.getResourceAsStream("/myProp.properties");

这篇关于用Java读取属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 00:09