java - 从类路径而不是从 resources/config.properties 检索属性

标签 java classpath

我目前有以下方法,它允许我选择已在 resources/config.properties 文件中定义的属性

private final Properties properties = new Properties();
{
    final ClassLoader loader = getClass().getClassLoader();
    try(InputStream config = loader.getResourceAsStream("Resources/config.properties")){
        properties.load(config);
    } catch(IOException e){
        throw new IOError(e);
    }
}

但我现在想从类路径中选择我的属性,因此我已将 config.properties 从资源中移出并将其直接放在 src 下。但我很难知道现在需要对我的方法进行哪些更改才能从类路径读取。

最佳答案

Check example here

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

    public class ReaderProp {
        public final Properties properties = new Properties();
        public ReaderProp()
        {
            final ClassLoader loader = getClass().getClassLoader();
            try(InputStream config = loader.getResourceAsStream("error.properties")){
                properties.load(config);
            } catch(IOException e){
                throw new IOError(e);
            }
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ReaderProp  readerProp = new ReaderProp();
            System.out.println(readerProp.properties.get("E1000_SE_ERROR-CODE"));// output E1000
        }
    }

Check error.properties
======================
E1000_SE_ERROR-CODE = E1000

enter image description here

关于java - 从类路径而不是从 resources/config.properties 检索属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51645892/

相关文章:

oracle - WildFly - 将 JAR 添加到类路径

java - 使用java将字符串从文件读取到数组列表

java - 从 FTPClient.getModificationTime() 解析日期字符串

java - 程序不提示输入字符串,但提示其他数据类型

java - 使用 NamedQuery 进行内连接?

Java NoClassDefFoundError 即使该类存在

java - 如何给java添加第三方java库

java - 使用 java 将一个 json 对象作为另一个对象的子对象

intellij-idea - 在 IntelliJ IDEA 中运行测试时出现 java.lang.NoSuchMethodError

java - 在 netbeans 中为 Maven 项目设置自定义运行时类路径