在 JAR 文件之外读取属性文件 - java 8 无法识别文件

Read properties file outside JAR file - java 8 not recognizing file

复制了与下面示例程序相同的场景。

我正在尝试读取位于 类 文件夹外的文件 Test.txt。我正在使用 getResourceAsStream 方法来定位文件,但无法识别。只要我的文件在 类 文件夹中,它就会识别。

InputStream propFileInpStream = LocateFile.class.getResourceAsStream("../../../"+PROP_FILE);

如果在 类 文件夹之外则无法识别

正在识别 类 文件夹结构中的任何位置

LocateFile.class.getResourceAsStream 将在 class 路径中查找文件。

如果您需要访问 class 路径之外的文件,那么,您可以将该文件的位置添加到 class 路径或使用绝对路径并使用 this thread to read it as a stream 中的建议。

这是正常的,完全符合预期。

Class.getResourceAsStream(name) 尝试查找具有给定名称的资源,而不是任意文件。资源是存在于应用程序类路径中的文件。如果该文件不在类路径中,则不能使用该方法从中检索 InputStream

你可以做的是使用 Java NIO.2 API with the help of Files.newInputStream(path):

Opens a file, returning an input stream to read from the file.

此方法将打开文件(而不是资源)进行读取。您可以使用静态工厂 Paths.get(first, more...) 获得一个 Path 实例。您可以给出文件的绝对路径或相对于 jar 文件位置的路径。

示例代码:

try (InputStream propFileInpStream = Files.newInputStream(Paths.get(path))) {
    // do something with the input stream
}

您需要对 class 路径之外的内容进行不同的处理。您可能想询问 JVM 您的 class 的字节码物理存储在哪里,然后从那里导航到您需要的文件。请注意,当 class 文件存储在 jar 中时,这会有所不同。

来自 http://www.exampledepot.com/egs/java.lang/ClassOrigin.html:(旧 link)

// Get the location of this class
Class cls = this.getClass();
ProtectionDomain pDomain = cls.getProtectionDomain();
CodeSource cSource = pDomain.getCodeSource();
URL loc = cSource.getLocation();  // file:/c:/almanac14/examples/

感谢大家的帮助,我刚刚更换了行

InputStream propFileInpStream = LocateFile.class.getResourceAsStream("..\\"+PROP_FILE);

进行了以下更改:

InputStream propFileInpStream = new FileInputStream("..\\"+PROP_FILE);