【问题标题】:loading config file from default package vs from classpath从默认包加载配置文件与从类路径加载
【发布时间】:2014-08-17 10:34:00
【问题描述】:

我在码头上的 JAX-RS 应用程序中加载配置文件时遇到了一个疯狂的错误。

public class Configuration {
    public static final Properties config = new Properties();

    static {
        config.clear();

        try (InputStream inputStream = Configuration.class.getClassLoader().getResourceAsStream("config.properties")) {
            config.load(inputStream);
        } catch (Exception ex) {
            Logger.error(ex);
        }
    }
}

如果我将config.properties 放在默认包中,它可以正常工作。但是当我用java -cp config.properties 加载它时,config 对象中没有任何内容。我已经检查了这些方法,但它不起作用。

ClassLoader.getSystemClassLoader().getResourceAsStream("config.properties");
ClassLoader.getSystemClassLoader().getResourceAsStream("/config.properties");
Configuration.class.getClassLoader().getResourceAsStream("config.properties");
Configuration.class.getClassLoader().getResourceAsStream("/config.properties");

奇怪的是,我在项目中使用 Tinylog 作为 Logger,TinyLog 以同样的方式加载了它的配置文件tinylog.properties

/* I found this from Tinylog source code */
Configurator.class.getClassLoader().getResourceAsStream("tinylog.properties");

我正在通过 java -cp tinylog.properties 提供 tinylog 配置。我的代码有什么问题吗?

【问题讨论】:

    标签: java classpath default-package tinylog


    【解决方案1】:

    -cp 选项采用目录和 jar 文件列表。它不需要属性文件。您需要将包含config.properties 文件的目录 放在类路径中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      相关资源
      最近更新 更多