ClassLoader.getSystemResourceAsStream和getClass()之间的区别.getResourceAsStream() [英] Difference between ClassLoader.getSystemResourceAsStream and getClass().getResourceAsStream()

查看:1195
本文介绍了ClassLoader.getSystemResourceAsStream和getClass()之间的区别.getResourceAsStream()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此代码:

/* 1 */ InputStream in1 = ClassLoader.getSystemResourceAsStream("foobar.txt");
/* 2 */ InputStream in2 = this.getClass().getResourceAsStream("/foobar.txt");

两者都返回相同的资源(我认为答案是是)?

Do both return the same resource (I think the answer's "yes")?

他们都访问相同的类路径吗?为什么#1中的方法名称得到系统 ResourceAsStream,但对于#2,它只是getResourceAsStream?

Do they both access the "same" classpath? Why is the method name in #1 "get System ResourceAsStream", but for #2 it's just "getResourceAsStream"?

谢谢

推荐答案

根据javadoc


打开读取,用于加载类的搜索
路径中指定名称的资源。此方法通过
系统类加载器查找资源(请参阅 getSystemClassLoader())。

用于加载的类加载器不一定是系统类加载器。在一个简单的桌面应用程序中,这可能是真的。但是webapps - 除其他外 - 通常具有更复杂的类路径层次结构,因此不一定相同。因此,在复杂的类路径中,返回的内容还将取决于在类路径中浮动的foobar.txt副本数量。

The classloader used to load this is not necessarily the system classloader. In a simple desktop app, this will probably be true. But webapps - amongst other things - typically have more complex classpath hierarchies and so that won't necessarily be the same. In a complex classpath, therefore what's returned will also depend on how many copies of 'foobar.txt' are floating around your classpath.

简短的回答是你不能假设他们会为同一资源返回一个流。

The short answer is that you can't assume that they will return a stream for the same resource.

这篇关于ClassLoader.getSystemResourceAsStream和getClass()之间的区别.getResourceAsStream()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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