【问题标题】:Accessing properties files outside the .jar?访问 .jar 之外的属性文件?
【发布时间】:2010-10-20 23:54:52
【问题描述】:

我有一个要放在一起的 .jar 文件。我想创建一个非常简单的 .properties 文件,其中包含用户名和其他内容等可配置的内容,以便他们可以手动编辑,而不必包含 GUI 编辑器。

我想做的是能够按以下顺序搜索:

  1. 指定的属性文件 (args[0])
  2. 当前目录(调用 Java 的目录)中的 MyApp.properties
  3. 用户目录中的 MyApp.properties(user.home 系统属性?)
  4. 存储应用程序 .jar 的目录中的 MyApp.properties

我知道如何访问 #1 和 #3(我认为),但是如何在运行时确定 #2 和 #4?

【问题讨论】:

    标签: java properties jar


    【解决方案1】:

    4,你可以试试这个。获取类路径:

    String classpath = System.getProperty("java.class.path");
    

    然后搜索你的应用jar的名字:

    int jarPos = classpath.indexOf("application.jar");
    

    解析出通往它的路径:

    int jarPathPos = classpath.lastIndexOf(File.pathSeparatorChar, jarPos) + 1;
    String path = classpath.substring(jarPathPos, jarPos);
    

    然后附加MyApp.properties。确保检查jarPos == -1,这意味着如果类路径(可能在您的开发环境中运行时)找不到该jar。

    【讨论】:

    • 已经搜索了 1 周,他们说的任何地方都使用Main.class.getProtectionDomain().getCodeSource(),这不起作用!!!至少不是在 Mac 上从 .app 文件的内容中......但这终于解决了我的问题......非常感谢......
    【解决方案2】:

    #2 是"user.dir" 系统属性。 #3 是“user.home”属性。

    #4 无论你如何处理它都有点杂乱无章。如果您从不在系统类路径上的 JAR 中加载了一个类,则可以使用另一种技术。

    CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
    if (src != null) {
      URL url = new URL(src.getLocation(), "MyApp.properties");
      ...
    } 
    else {
      /* Fail... */
    }
    

    【讨论】:

    • @erickson 它有效!但是如果我在 jar 和外部目录中有 MyApp.properties(不在任何包中)。那怎么读呢?
    【解决方案3】:

    对于当前工作目录:

    new File(".");
    

    对于当前目录下名为 MyApp.properties 的文件:

    new File(new File("."), "MyApp.properties");
    

    【讨论】:

    • 可行,但更短的方法是传递空字符串 (new File(""))
    猜你喜欢
    • 2019-04-23
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多