运行 jar 时覆盖属性文件

Override properties file when running jar

我正在尝试从我一直在处理的包中创建一个 .JAR,但遇到了 运行 问题。我希望用户能够修改程序 运行 的属性。

我的包的文件夹结构如下所示:

├───src
│   ├───main
│   │   ├───java
(...)
│   │   └───resources
│   │           dbinterface.properties

并且我想用用户放置在与 jar 相同的文件夹中(或放在它旁边的 ./config 文件夹中的文件)覆盖 dbinterface.properties 文件。

我曾尝试将 . 添加到 MANIFEST.MF 中的类路径,但不幸的是,那没有用。

我会在 属性 文件读取方法中实现这样的行为。您可以先尝试在用户可以创建的位置读取 属性 文件,如果找不到则回退到原始默认文件。类似于:

FileInputStream propFile;
try {
    propFile = new FileInputStream(new File("dbinterface.properties"));
} catch (FileNotFoundException e) {
    propFile = new FileInputStream(new File("resources/dbinterface.properties"));
}
Properties p = new Properties();
p.load(propFile);
propFile.close();

存储用户可编辑属性的最佳位置是用户主目录。在 Java 中,我们可以通过 System.getProperty("user.home") 独立于系统访问用户主页。这指向 linux 上的 /home/$USER 和 Windows 上的 %USERPROFILE%。所有其他 OS 也受支持。

You could first try to read the property file at the location the user could create, and fallback to the original default one if not found. - Galcoholic

I would like to avoid this. - padrino

为什么?

这是最好的方法:

  • 首先阅读您随程序删除的属性文件,
  • 然后(尝试)读取您的用户从 new File(System.getProperty("user.home"),".myProgram/dbinterface.properties") 更改的设置 (这基本上是@Galcoholic 建议的另一种方式)

当使用 Properties class 从 JVM 加载它们时,设置将自动合并。