Loading files with ClassLoader

邮差的信 提交于 2019-11-27 21:31:12

getSystemResource is static because it will use the system classloader, which is available statically. (ClassLoader.getSystemClassLoader)

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.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.

EDIT: I usually find the URL less useful than an InputStream, so I use getResourceAsStream instead of getResource. YMMV

You've mentioned several different things here, so let's sort them out.

1) Creating a "file:" URL based on "user.dir"

The "user.dir" property refers to the current working directory -- wherever the user might have been when s/he started the app. Chances are good that files written here will disappear between two runs (because the user might run from a different directory).

The "user.home" property refers to the user's home directory -- which should remain the same between runs.

In either case, use a File object to open files, don't muck around with creating a "file:" URL. You get no benefit, and as you can see, you have to write messy code to access it.

2) Retrieving a resource via the classloader

This is meant to retrieve files that are packaged with your application -- read-only files. As you have seen, there are multiple variants. I prefer using the following, because I assume that a class will want to load a file that's packaged with it.

InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!