getResourceAsStream for "/" in windows and linux

本文探讨了Java中使用getClass().getClassLoader().getResource()方法加载资源文件时遇到的问题,并解释了正确的路径配置方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

windows:

projectname/config/xxx.properties

classpath:.../config

TestListener.class.getClassLoader().getResource("/xxx.properties")

InputStream is = TestListener.class.getClassLoader().getResourceAsStream("/xxx.properties");

 

linux:

classpath:.../config

 

TestListener.class.getClassLoader().getResource("xxx.properties")

InputStream is = TestListener.class.getClassLoader().getResourceAsStream("xxx.properties");

 

TestListener.class.getClassLoader().getResource("/") 会返回null

 ========

http://www.coderanch.com/t/493235/java/java/getClass-getClassLoader-getResource-path-always

getClass().getClassLoader().getResource(path) always return null, even when the path is correct

Daniel Gallant
Greenhorn

Joined: Sep 09, 2009
Posts: 27
I'm having an issue with the following code. the getClass().getClassLoader().getResource(path) always throws an exception, but the path used (and printed in the error message) are correct.

  1.     protected ImageIcon createImageIcon(String path, String description) {   
  2.         java.net.URL imgURL = getClass().getClassLoader().getResource(path);   
  3.         if (imgURL != null) {   
  4.             return new ImageIcon(imgURL, description);   
  5.         } else {   
  6.             System.err.println("Couldn't find file: " + path);   
  7.             return null;   
  8.         }   
  9.     }  


Thanks for all your help!
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 23372

Hi Daniel,

"Correct" can be a relative term! The path should be relative to a location on the classpath; i.e., it's a path from the root of a jar file, or a path from the directory on the classpath. An absolute path from the root of your disk (for instance) will not work.


[Jess in Action][AskingGoodQuestions]
Daniel Gallant
Greenhorn

Joined: Sep 09, 2009
Posts: 27
D'Oh!!

I knew it would be something simple.

Thanks for your help! I really appreciate it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值