【发布时间】: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