简体   繁体   English

写入包含在Jar文件中作为资源的Java Properties文件

[英]Writing to Java Properties file contained as a Resource in a Jar File

Is there a way to modify the property values in a Properties file that is stored in a Jar file as a Resource? 有没有办法修改作为资源存储在Jar文件中的属性文件中的属性值?

This is the scenario that I am trying to handle. 这是我想要处理的场景。 I have a properties file stored as a resource in my Jar file. 我有一个属性文件存储在我的Jar文件中作为资源。 There are some system specific properties, for example, paths. 有一些特定于系统的属性,例如路径。 I want to be able to change this for the system that I want the Jar file to run on. 我希望能够为我希望运行Jar文件的系统更改此设置。

The best solution would be to call a class/method that is internal to the Jar file that will modify the resource file that is contained in the Jar. 最好的解决方案是调用Jar文件内部的类/方法,该类文件将修改Jar中包含的资源文件。 Another solution would be to run a utility program on the Jar file that will modify the property file and re-Jar everything. 另一个解决方案是在Jar文件上运行一个实用程序,它将修改属性文件并重新生成所有内容。 This will be a one-time setup process that I run on the Jar file. 这将是我在Jar文件上运行的一次性设置过程。

Use the preferences API to store changes: http://java.sun.com/j2se/1.5.0/docs/api/java/util/prefs/package-frame.html 使用首选项API存储更改: http//java.sun.com/j2se/1.5.0/docs/api/java/util/prefs/package-frame.html

Edit after re-reading the question: are you in a situation where you want to send out the JAR to potentially many people and have it customized on install? 重新阅读问题后进行编辑:您是否希望将JAR发送给潜在的许多人并在安装时进行自定义? If yes, then prefs is the way to go. 如果是,那么prefs是要走的路。

If, instead, you're looking to customize for a relatively small number of deployments, then it's probably better to do the customization at build-time. 相反,如果您希望针对相对较少的部署进行自定义,那么在构建时进行自定义可能会更好。

I think you may find the Apache Commons Configuration project of use. 我想你可能会发现使用的Apache Commons Configuration项目

You can set this up to use properties files, and to have the concept of a system and a user properties file . 您可以将其设置为使用属性文件,并具有系统和用户属性文件的概念。 You can then deploy to your system property file, and this is overridden by the user property file. 然后,您可以部署到系统属性文件,并由用户属性文件覆盖。 Writing a property will modify the user properties file. 编写属性将修改用户属性文件。

So you deploy your system properties file with your defaults, and changes are maintained in the overriding user properties file. 因此,使用默认值部署系统属性文件,并在覆盖的用户属性文件中维护更改。 I've used this in the past for exactly what you're doing, and it works very nicely. 我过去常常使用它来完成你正在做的事情,而且效果非常好。 There's a huge number of ways to configure this library, so it's worth looking at the examples and FAQ. 配置此库有很多方法,因此值得查看示例和常见问题解答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM