在通过 getClass().getResourceAsStream 读取的 .properties 文件中存储更改 [英] Storing changes in .properties file that has been read via getClass().getResourceAsStream

查看:65
本文介绍了在通过 getClass().getResourceAsStream 读取的 .properties 文件中存储更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个从 .properties 文件读取属性的 Java Web 应用程序.由于我不知道 .properties 文件的绝对路径,因为它取决于应用程序将来运行的环境,所以我必须使用getClass().getResourceAsStream"加载它:

I am writing a java web application that reads properties from a .properties file. Since I do not know the absolute path of the .properties file, because it depends on the environment the application will run on in the future, I have to load it with "getClass().getResourceAsStream":

Properties props = new Properties();
props.load(getClass().getResourceAsStream("test.properties"));
message = props.getProperty("testdata");

这按预期工作.现在我想更改文件中 testdata 的值.但是我无法打开要写入的输出流,因为我仍然不知道 .properties 文件的路径.

This works as expected. Now I want to change the value for testdata in the file. But I cannot open an Outputstream to write to, because I still don't know the path of the .properties file.

props.setProperty("testdata", "foooo");
props.store(new FileOutputStream("?????"), null);

有没有办法获取文件的路径,或者我可以以某种方式使用已建立的属性对象?欢迎任何允许我更改 .properties 文件的想法.

Is there a way to get the path of the file or can I use the established Properties-object somehow? Any ideas are welcome that allow me to change the .properties file.

推荐答案

您可以通过使用 getResource() 而不是使用 getResourceAsStream() 来获取 URL

You can get an URL by using getResource() rather than using getResourceAsStream()

然后您可以使用该 URL 读取和写入您的属性文件.

You can then use that URL to read from and write to your properties file.

File myProps = new File(myUrl.toURI());
FileInputStream in = new FileInputStream(myProps); 

这篇关于在通过 getClass().getResourceAsStream 读取的 .properties 文件中存储更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆