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

查看:18
本文介绍了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).

推荐答案

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

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"的类加载器和 x.y.z 包中加载资源(它需要与该包中的类位于同一目录中).

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 包(系统包)中.

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 只是在从 getResource 返回的 URL 上调用openStream"并返回那个.

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天全站免登陆