Where to store .properties files for Java?
The Java tutorial on using properties talks about how to use the Properties class. In the tutorial it shows the properties being written to a file called "defaultProperties". So what is a good name and location for the properties file?
I usually write one of two java applications: a system utility or a user program. I think most system utilities would have a file in /etc/myfile.proper开发者_StackOverflow社区ties
and most user programs would create a ~/.myfile.properties
. However, these paths would not work in Windows. Is there a more generic way of defining these details to make the code platform independent?
If you are talking about keeping external property file to configure your app then I would suggest
System.getProperty("user.home")+File.separator+ "yourappname"+File.separator+"name.properties"
of if you are talking about property file placed internal to your project keep it in default package
.
OR
other options are using XML file, or Preference
In this case I would use the Preferences
API instead of Properties
.
Preferences
allows you to store/retrieve user and system settings and automatically handles the persistence for you. The persistence is platform specific; for Windows it uses the registry and for Unix it uses hidden files.
Here are a couple of alternate solutions:
- Read the property file from the classpath
- Pass the path to the property file as a startup argument to the application
Reading it from the classpath gives you flexibility, since you can then include it in the jar itself or specify it when the application starts.
If your are bundling the props file as part of the app and is for read-only then put it in jar file. If you have to also update it then make it available through file:/// url and pass the file path as a JVM (-DfileUrl=...) argument.
Look at this post on how to read the props file from a JAR in classpath: Reading properties file from JAR directory
Using jndi is a good solution. Runtime config via admin console of webserver. Webapp will pickup changes as soon as you get a property, You don't have to restart the application.
精彩评论