存储已通过getClass()。getResourceAsStream读取的.properties文件中的更改

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

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

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

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

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

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

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

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

等等。

Properties类包含一个store方法,可用于将属性保存回getClass()中读取的流.getResourceAsStream(“test.properties”)。