问题描述
这个问题一直困扰着我。我必须在我的java应用程序中加载几个文件,到目前为止我工作的唯一方法是这样的:
This problem has been bugging me for a while. I have to load a couple files in my java app, and the only way I got working so far looks like this:
URL hsURL;
if(System.getProperty("os.name").toLowerCase().contains("windows")) {
hsURL = new URL("file:/" + System.getProperty("user.dir") + "/helpsets/helpset.hs");
}
else {
hsURL = new URL("file://" + System.getProperty("user.dir") + "/helpsets/helpset.hs");
}
但这很丑陋可怕。有一段时间我以为我有这个工作:
But this is ugly and terrible. For a while I thought I had this working:
hsURL = ClassLoader.getSystemResource("helpsets/helpset.hs");
但是由于某些原因它不再有效(我必须改变一些东西而不是注意到它。它返回null 。
But that no longer works for some reason (I must have changed something and not noticed. It returns null.
我应该使用getResource()而不是getSystemResource()(如果是这样,为什么getSystemResource()是静态的而不是getResource())?
Should I be using getResource() instead of getSystemResource() (if so, why is getSystemResource() static but not getResource())?
我正在使用eclipse,我尝试在构建路径(classpath)中包含该文件夹而不包括它,它似乎没有什么区别。
I am using eclipse and I have tried including the folder in the build path (classpath) and not including it, it doesn't seem to make a difference.
推荐答案
getSystemResource
是静态的,因为它将使用 system 类加载器,静态可用。( ClassLoader.getSystemClassLoader
)
getSystemResource
is static because it will use the system classloader, which is available statically. (ClassLoader.getSystemClassLoader
)
如果您的资源在类路径中可用,我建议使用来自相应类的 ClassLoader.getResource()
或 Class.getResource
,例如
If your resource is available in the classpath, I would suggest using ClassLoader.getResource()
or Class.getResource
from an appropriate class, e.g.
Foo.class.getResource("/helpsets/helpset.hs");
( ClassLoader.g etResource
是绝对的; Class.getResource
是相对于该类的包,除非您在前面加上'/'。)
(ClassLoader.getResource
is "absolute"; Class.getResource
is relative to the package of the class unless you prefix it with a '/'.)
如果这不起作用,请根据类路径以及文件的位置发布应用程序的配置方式。
If this doesn't work, please post how your app is configured in terms of the classpath, and where your file is.
编辑:我通常发现URL不太有用而不是 InputStream
,所以我使用 getResourceAsStream
而不是 getResource
。 YMMV
I usually find the URL less useful than an InputStream
, so I use getResourceAsStream
instead of getResource
. YMMV
这篇关于使用ClassLoader加载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!