如何在Java中引用资源? [英] How do I reference a resource in Java?

查看:163
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆