【问题标题】:How can I retrieve an external .properties file in Java?如何在 Java 中检索外部 .properties 文件?
【发布时间】:2015-04-14 16:46:28
【问题描述】:

我在尝试从项目外部目录加载属性文件时遇到以下问题。

所以我的项目结构如下:

PROJECT-ROOT
     |
     |
     |-----> confi
     |
     |------> src
               |
               |
               |------> mainPkg (the package name)
                           |
                           |
                           |------> Main (the main class containing the main() method)

好的,所以在主类中我需要加载位于项目根文件夹之外的 config.properties 文件(例如在同一级别)。所以我认为 config.properties 文件在应用程序类路径之外。

所以我尝试做这样的事情:

InputStream input = new FileInputStream("../../config.properties");

InputStream input = new FileInputStream("../../../config.properties");

但不工作,因为我得到以下异常:

java.io.FileNotFoundException: ..\..\config.properties (Impossibile trovare il file specificato)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:120)
    at java.io.FileInputStream.<init>(FileInputStream.java:79)
    at mainPkg.Main.main(Main.java:41)

如果我使用这样的绝对路径,它会起作用:

InputStream input = new FileInputStream("C:\\Projects\\edi-sta\\config.properties");

并正确检索 InputStrea 对象。但这对我的目的不利,因为我不能使用绝对路径。

如何使用相对路径检索位于项目根文件夹同一级别的 config.properties 文件?

【问题讨论】:

  • 注意:您的相对路径是相对于执行期间的工作目录——而不是包含源文件的目录。在开发过程中,在 IDE 中,您可以在启动器中设置工作目录。在生产中,您可以使用 MyClass.class.getProtectionDomain().getCodeSource().getLocation() 从 jar 文件位置计算绝对路径。
  • 如果属性文件不包含在 jar 本身中,则应从当前工作目录中读取或使用命令行参数指定。

标签: java file jakarta-ee inputstream properties-file


【解决方案1】:

您的项目根目录将是您程序的当前工作目录。所以,你应该试试

InputStream input = new FileInputStream("../config.properties");

但这不是推荐的设置。该文件应放置在项目目录中,并且在您发布应用程序时应进行适当的 jar 处理。

【讨论】:

    【解决方案2】:

    如果 config.properties 文件不在类路径中,您应该使用文件夹作为起点(例如用户文件夹或当前工作文件夹)。

    如果文件在您的类路径中,您可以尝试使用 this.class.getResourceAsStream 或 this.class.getClassLoader().getResourceAsStream()。

    在一个简单的上下文中,两个调用之间的区别非常简单: this.class.getResourcesceAsStream("config.properties") 将返回 InputStream 当且仅当文件位于调用该方法的同一类包中。

    只有当文件位于类路径的根目录时,this.class.getClassLoader().getResourceAsStream("config.properites") 才会返回相同的 InputStream。在这种情况下,您必须将“config”文件夹添加到类路径

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 2011-05-31
      • 2015-07-01
      • 2021-11-05
      • 2021-03-30
      相关资源
      最近更新 更多