在 Java 中读取属性文件

2022-08-31 08:18:56

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

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)

谢谢,尼科斯


答案 1

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

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

答案 2


您可以在此页面上找到相关信息:
http://www.mkyong.com/java/java-properties-file-examples/

Properties prop = new Properties();
try {
    //load a properties file from class path, inside static method
    prop.load(App.class.getClassLoader().getResourceAsStream("config.properties"));

    //get the property value and print it out
    System.out.println(prop.getProperty("database"));
    System.out.println(prop.getProperty("dbuser"));
    System.out.println(prop.getProperty("dbpassword"));

} 
catch (IOException ex) {
    ex.printStackTrace();
}