Include A Properties File With A Jar File

亡梦爱人 提交于 2019-12-03 07:17:20

You are right. If the properties are intended to be modifiable by the user, then putting them in a properties file in the JAR is not going to work

There are a couple of approaches:

  • You could put the properties in a property file that you store in the file system. The problem is figuring out where in the filesystem to store them:

    • On UNIX / Linux there are conventions for where to store system-wide and per-user configuration properties, but these are a bit loose, and in a bit of a state of flux (e.g. certain "desktop" frameworks have their own preference mechanisms.

    • There are similar conventions for Windows I believe.

    • The problem with approach can be permissions issues (you don't want one user changing another's preferences), and possibly even issues with read-only file systems and the like.

    • If you are going to use a property file in the filesystem, it is a bad idea to hardwire the location into your code. Make it configurable via a command line argument and/or a "system property" that can be set using the -D option.

  • On Windows, you could put the properties into the Windows registry. But you will need to use 3rd party libraries to do this. And of course, this is not portable - it won't work on a non-Windows platform.

  • You could use the Java Preferences API. This is portable across multiple platforms but it is a Java-centric solution; i.e. it doesn't fit well with the platform's "normal way" of doing things.

In short, there is no solution that is ideal from all perspectives.


But once you've decided how to store your preferences, you could write your application so that it uses the properties file in your JAR file to provide default or initial settings.

You can load a property file from the classpath instead. This enables you to bundle the property file inside the jar, but also outside the jar. It just needs to be on the classpath of the running application.

You can do so in the following way:

Properties props = new Properties();
InputStream inputStream = this.getClass().getClassLoader()
        .getResourceAsStream(propFileName);

props.load(inputStream);
ekim

instead of

in = DatabaseHandler.class.getResourceAsStream("database.properties");

try

in = DatabaseHandler.class.getResourceAsStream("/database.properties");
Chris

Do not hardcode the location of property file. Your approach should be to stream the file from classpath.

If not, the better way would be to point to a URL which returns the properties information in a specific data format (say JSON).

If you have JAR check this out.

If your application is WAR check properties in WAR.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!