如何在 Java 中引用资源?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3727994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I reference a resource in Java?
提问by Chris Knight
I need to read a file in my code. It physically resides here:
我需要在我的代码中读取一个文件。它实际驻留在此处:
C:\eclipseWorkspace\ProjectA\src\com\company\somePackage\MyFile.txt
I've put it in a source package so that when I create a runnable jar file (Export->Runnable JAR file) it gets included in the jar. Originally I had it in the project root (and also tried a normal sub folder), but the export wasn't including it in the jar.
我已经把它放在一个源包中,这样当我创建一个可运行的 jar 文件(导出->可运行的 JAR 文件)时,它就会被包含在 jar 中。最初我将它放在项目根目录中(并且还尝试了一个普通的子文件夹),但是导出时没有将它包含在 jar 中。
If in my code I do:
如果在我的代码中我这样做:
File myFile = new File("com\company\somePackage\MyFile.txt");
the jar file correctly locates the file, but running locally (Run As->Java Main application) throws a file not found exception because it expects it to be:
jar 文件正确定位了该文件,但在本地运行(Run As->Java Main 应用程序)会引发文件未找到异常,因为它期望它是:
File myFile = new File("src\com\company\somePackage\MyFile.txt");
But this fails in my jar file. So my question is, how do I make this concept work for both running locally and in my jar file?
但这在我的 jar 文件中失败了。所以我的问题是,如何使这个概念既适用于本地运行又适用于我的 jar 文件?
采纳答案by Jon Skeet
Use ClassLoader.getResourceAsStream
or Class.getResourceAsStream
. The main difference between the two is that the ClassLoader
version always uses an "absolute" path (within the jar file or whatever) whereas the Class
version is relative to the class itself, unless you prefix the path with /.
使用ClassLoader.getResourceAsStream
或Class.getResourceAsStream
。两者之间的主要区别在于ClassLoader
版本始终使用“绝对”路径(在 jar 文件或其他文件中),而Class
版本是相对于类本身的,除非您在路径前加上 /。
So if you have a class com.company.somePackage.SomeClass
and com.company.other.AnyClass
(within the same classloader as the resource) you could use:
因此,如果您有一个类com.company.somePackage.SomeClass
并且com.company.other.AnyClass
(在与资源相同的类加载器中)您可以使用:
SomeClass.class.getResourceAsStream("MyFile.txt")
or
或者
AnyClass.class.getClassLoader()
.getResourceAsStream("com/company/somePackage/MyFile.txt");
or
或者
AnyClass.class.getResourceAsStream("/com/company/somePackage/MyFile.txt");
回答by Christian
If I have placed i file in a jar file, it only worked if and only if I used
如果我已将 i 文件放在 jar 文件中,则它仅在我使用时才有效
...getResourceAsStream("com/company/somePackage/MyFile.txt")
If I used a File object it never worked. I got also the FileNotFound exception. Now, I stay with the InputStream object.
如果我使用 File 对象,它永远不会工作。我也得到了 FileNotFound 异常。现在,我继续使用 InputStream 对象。