Java:在类路径上加载和编辑属性文件

标签 java properties classpath

我想将一些属性保留到属性文件中,以防它们在程序运行期间发生更改。现在我正在尝试这样做:

Properties properties = new Properties();

    try (FileInputStream in = new FileInputStream("classpath:app.properties")) {
        properties.load(in);
    } catch (IOException e) {
        logger.error("", e);
    }

    properties.setProperty("word", "abc");

    try (FileOutputStream out = new FileOutputStream("classpath:app.properties")) {
       properties.store(out, null);
    } catch (IOException e) {
        logger.error("", e);
    }

但是好像不行。我做错了什么?

最佳答案

为了能够读取和写入位于 resources 文件夹中的属性文件(在标准 Maven 项目结构中),您可以使用以下命令:

// of course, do not forget to close the stream, after your properties file has been read.
properties.load(Runner.class.getClassLoader().getResourceAsStream("app.properties"));

修改属性文件后,您可以使用如下内容:

Runner.class.getClassLoader().getResource("app.properties").getFile()

获取文件的绝对路径。

附注只是为了确保您检查的是正确的文件。您不应检查 resources 文件夹中的文件。修改后的文件将与您的类一起放置在根文件夹中,例如 targetout

关于Java:在类路径上加载和编辑属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26657742/

相关文章:

java - Android: fragment 交互监听器出错

java - 在 IntelliJ 中从类路径外部的 JAR 加载资源文件

java - Weblogic 应用程序从同一 web 应用程序中的其他 jar 加载实用程序 jar 类

java - 是否可以使用 ant 覆盖 xml 文件中的属性?

c# - 找出 Windows Server 2008 中的电影数据速率

python - 为什么从实例获取类属性会引发 AttributeError?

java - 错误: Could not find or load main class IntelliJIdea

java - 如何将调用的命令/程序的输出重定向到 log4j?

java - 我搜索实现函数获取字符串中出现次数最多的字符并对其进行计数

java - 如何使用点 (.) 根据宽度和高度打印一条线