Java 应用程序的配置文件

6 java exe properties classpath

我正在构建一个 Java 应用程序,目的是将来将其打包为 Windows 可执行文件。我的 NetBeans 项目结构可以在这里看到 我目前正在使用 getResourceAsStream() 读取 config.properties。我不知道不能以类似的方式写入该文件。有人能建议一种实现此目标的方法吗?或者是否需要采用不同的方法来解决我的问题?谢谢。

小智 5

我认为你可以用它java.util.properties来解决你的问题;要写入您的属性,首先创建一个新Properties对象,load它们通过您的InputStream,使用诸如setProperty添加到您的配置之类的方法,最后使用store写入它们。

例子:

File appConfig = new File("a_file");
FileInputStream propsInput = new FileInputStream("a_file");

Properties prop = new Properties();

prop.load(propsInput);

try (Writer inputStream = new FileWriter(appConfig)) {

   // Setting the properties.
   prop.setProperty("A_PROP", "A_VALUE");

   // Storing the properties in the file with a heading comment.
   prop.store(inputStream, "INFORMATION!!!");

} catch (IOException ex) {
   ex.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)