【问题标题】:Property file is not found and throwing exception?找不到属性文件并抛出异常?
【发布时间】:2016-05-14 11:41:00
【问题描述】:

我正在尝试读取属性文件以获取值。但是,代码抛出异常。

例外

Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.cisco.installbase.hiveconnector.ReadProperties.getInstance(ReadProperties.java:28)
    at com.cisco.installbase.hiveconnector.MainApp.main(MainApp.java:7)
Caused by: java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:434)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties.load(Properties.java:341)
    at com.cisco.installbase.hiveconnector.ReadProperties.<init>(ReadProperties.java:16)
    at com.cisco.installbase.hiveconnector.ReadProperties.<init>(ReadProperties.java:12)
    at com.cisco.installbase.hiveconnector.ReadProperties$PropHolder.<clinit>(ReadProperties.java:23)
    ... 2 more

ReadProperties.java

package com.cisco.installbase.hiveconnector;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

public class ReadProperties {

    private final Properties props = new Properties();

    private ReadProperties()
    {
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties");
        try{
            props.load(in);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    private static class PropHolder{
        private static final ReadProperties INSTANCE = new ReadProperties();
    }

    public static ReadProperties getInstance()
    {
        return PropHolder.INSTANCE;
    }

    public String getProperty(String key)
    {
        return props.getProperty(key);
    }

    public Set<String> getAllPropertyNames()
    {
        return props.stringPropertyNames();
    }

    public boolean containsKey(String key)
    {
        return props.containsKey(key);
    }
}

我的 prop 文件的目录结构和位置

谁能帮我确定需要放置属性文件的位置。

【问题讨论】:

    标签: java maven properties properties-file


    【解决方案1】:

    您的文件config.properties 不在类路径中,因此无法通过this.getClass().getClassLoader().getResourceAsStream("config.properties") 加载

    放在src/main/resources

    请咨询Standard Maven directory layout

    【讨论】:

    • 我在我的项目中看不到资源文件夹。我应该创建文件夹
    • 是的,您必须创建此文件夹并将您的 config.properties 文件移动到那里
    • @dataEnthusiast 如果这个答案解决了你的问题,请mark it as accepted(点击旁边的复选标记)
    【解决方案2】:

    如果这是一个典型的 maven 项目,那么属性文件位于 src/main/resources 下。 Maven 会为你将它移到类路径中。

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多