【问题标题】:Read external properties file Java/Linux读取外部属性文件 Java/Linux
【发布时间】:2018-12-18 17:46:33
【问题描述】:

我的任务是编写一些代码,这些代码将根据我所处的环境(生产或测试)提取属性文件。所以jar文件在每个环境中都是相同的,但是一些变量会根据jar执行的环境而改变。导演看起来像这样:

[ProgramOne.jar ProgramTwo.jar ProgramThree.jar mypropertiesfile.properties]

我需要将这些 jar 中的每一个都读取到属性文件中。我正在阅读这样的内容:

   try(InputStream theResourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("mypropertiesfile.properties"))

我还没有访问这些环境的权限,并且将有一个非常小的窗口来实现此代码。我的问题是,鉴于我的情况,这是读取属性文件的正确方法吗?这甚至会起作用吗?我已经尝试在本地机器上加载文件,但一切都返回 null。

【问题讨论】:

    标签: java linux jar properties


    【解决方案1】:

    如果它不能在您的机器上运行,那么它可能无法在另一台机器上运行。

    当我认为您想从同一目录中的外部文件加载属性时,您似乎正在尝试从 Jar 加载资源。

    试试这个:
    with test.properties 在与 Jar 相同的目录中,有一个属性 my-property=this is a test

    public class Main {
        public static void main(String[] args){ new Main().test(); }
    
        /** Usually gets the `JAR` directory or the `bin` when running in IDE */
        public String getCodeSourcePath() throws SecurityException, URISyntaxException {
            return getClass().getProtectionDomain().getCodeSource().getLocation()
                .toURI().getPath();
        }
    
        public void test() {
            // TODO handle exceptions, unlikely to occur unless you do something weird
            String jarPath = getCodeSourcePath();
    
            Properties properties = new Properties();
            File file = new File(jarPath, "test.properties");
            try (FileInputStream fis = new FileInputStream(file);) {
                properties.load(fis);
            }
            System.out.println(properties.getProperty("my-property"));
    
        }
    }
    

    输出:this is a test

    【讨论】:

    • @MarcusHolden 没问题
    猜你喜欢
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多