9

关于 Java EE 中 ClassLoader 获取资源路径问题

 4 years ago
source link: https://www.v2ex.com/t/778724
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Java

关于 Java EE 中 ClassLoader 获取资源路径问题

  xiaopanzi · 11 小时 55 分钟前 · 335 次点击

下面均假设资源文件均在main目录下面的resources里面:

在 Java SE 中,如果使用ClassLoader.getResource获取资源(包括ClassLoader.getResourceAsStream,下面不再重复),其路径不能以"/"开头。换言之,如果有个foo.txt的话,代码

getClass().getClassLoader().getResource("/foo.txt")

将返回null

但是我发现,如果在 Java EE 项目中,同样的情况,加不加"/"均能正常获取资源文件,这是为什么?


  • OpenJDK 11
  • Tomcat 9
  • Servlet 4.0

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK