如何在Java中引用资源? [英] How do I reference a resource in Java?
问题描述
C:\eclipseWorkspace\ProjectA\src\com\company\somePackage\\ \\ MyFile.txt
我把它放在一个源码包中,这样当我创建一个可运行的jar文件(Export-> Runnable JAR文件)它包含在jar中。原来我在项目的根目录(也尝试了一个普通的子文件夹),但出口没有包括在罐子里。
如果在我的代码I请执行以下操作:
文件myFile = new File(com \\company\\somePackage\\MyFile。文本);
jar文件正确地定位了文件,但是在本地运行(Run As-> Java Main application)throws一个文件没有找到异常,因为它期望它是:
文件myFile =新文件(src\\com\\ \\\company\\somePackage\\MyFile.txt);
但是这在我的jar文件中失败了。所以我的问题是,我该如何使这个概念在本地运行,并在我的jar文件?
使用 ClassLoader.getResourceAsStream
或 Class.getResourceAsStream
。两者之间的主要区别在于 ClassLoader
版本总是使用一个绝对路径(在jar文件中或其他),而 Class code>版本是相对于类本身,除非你在/前面加上路径。
所以如果你有一个类 com。您可以使用company.somePackage.SomeClass
和 com.company.other.AnyClass
(在资源相同的类加载器中):
$ b $ pre $
SomeClass.class.getResourceAsStream(MyFile.txt)
$ b $或b
$ b $ pre $ AnyClass.class.getClassLoader
.getResourceAsStream COM /公司/ somePackage / MyFile.txt的);
或
AnyClass.class.getResourceAsStream( / COM /公司/ somePackage / MyFile.txt的);
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.
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:
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?
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 /.
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:
SomeClass.class.getResourceAsStream("MyFile.txt")
or
AnyClass.class.getClassLoader()
.getResourceAsStream("com/company/somePackage/MyFile.txt");
or
AnyClass.class.getResourceAsStream("/com/company/somePackage/MyFile.txt");
这篇关于如何在Java中引用资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!