我想将一些属性保留到属性文件中,以防它们在程序运行期间发生更改。现在我正在尝试这样做:
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
文件夹中的文件。修改后的文件将与您的类一起放置在根文件夹中,例如 target
或 out
。
关于Java:在类路径上加载和编辑属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26657742/