在Java中加载资源的首选方式 [英] Preferred way of loading resources in Java

查看:99
本文介绍了在Java中加载资源的首选方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Java中加载资源的最佳方法:

I would like to know the best way of loading a resource in Java:


  • this.getClass( ).getResource()(或getResourceAsStream())

  • Thread.currentThread()。getContextClassLoader()。getResource(name)

  • System.class.getResource(name)

  • this.getClass().getResource() (or getResourceAsStream()),
  • Thread.currentThread().getContextClassLoader().getResource(name),
  • System.class.getResource(name).

推荐答案

根据你的需要制定解决方案...

Work out the solution according to what you want...

有两件事 getResource / getResourceAsStream()将从调用的类中获取...

There are two things that getResource/getResourceAsStream() will get from the class it is called on...


  1. 班级装载机

  2. 起始位置

所以如果你这样做

this.getClass().getResource("foo.txt");

它将尝试从与this类相同的包中加载foo.txt this类的类加载器。如果你在前面放了一个/,那么你绝对是引用资源。

it will attempt to load foo.txt from the same package as the "this" class and with the class loader of the "this" class. If you put a "/" in front then you are absolutely referencing the resource.

this.getClass().getResource("/x/y/z/foo.txt")

将从类加载器中加载资源this和xyz包(它需要与该包中的类位于同一目录中)。

will load the resource from the class loader of "this" and from the x.y.z package (it will need to be in the same directory as classes in that package).

Thread.currentThread().getContextClassLoader().getResource(name)

将加载上下文类加载器但是不会根据任何包解析名称(必须绝对引用)

will load with the context class loader but will not resolve the name according to any package (it must be absolutely referenced)

System.class.getResource(name)

将使用系统类加载器加载资源(它必须绝对引用,因为你赢了不能把任何东西放到java.lang包中(System的包)。

Will load the resource with the system class loader (it would have to be absolutely referenced as well, as you won't be able to put anything into the java.lang package (the package of System).

看看源代码。还表明getResourceAsStream只是调用 openStream上从getResource返回的URL并返回该值。

Just take a look at the source. Also indicates that getResourceAsStream just calls "openStream" on the URL returned from getResource and returns that.

这篇关于在Java中加载资源的首选方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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