简体   繁体   English

getResourceAsStream返回null吗?

[英]getResourceAsStream returns null?

I saw same posts like this but any of them could resolve my problem. 我看到了类似的帖子,但是任何一个都可以解决我的问题。 I have my environment.properties which i want to access by: 我有我要访问的environment.properties:

InputStream inputStream = this.getClass().getResourceAsStream("/support/environment.properties");

inputStream is always receiving null. inputStream始终接收null。 This is my project structure 这是我的项目结构

MyProject
->src
-->test
--->java
---->com.desp.automation.config (package)
----->CrossAutomationConfigTest
-->main
--->resources
---->support
----->environment.properties

Do you know what's happening ? 你知道发生了什么吗? I would appreciate your help. 多谢您的协助。 Regards 问候

This happens to me all the time! 这一直在我身上发生! The actual path to the resource depends on the class loader meaning it depends on whether you are running in pure java, or a web container. 资源的实际路径取决于类加载器,这取决于您是在纯Java还是Web容器中运行。 I usually nail it by playing with the path to find it...things to try: 我通常通过玩找到它的路径来钉住它...尝试的东西:

(1) /resoures/support/... (2) / main/resources/support/... (3) the above without a leading / (1)/ resoures / support / ...(2)/ main / resources / support / ...(3)以上没有引号/

I think the requirement for the leading / depends on whether you are calling getResourceAsStream from a static or non-static method and whether the resources are packaged in an archive (zip/jar/war) or whether the app is unarchived into files in the deployment environment. 我认为前导/的要求取决于您是从静态方法还是从非静态方法调用getResourceAsStream,以及资源是否打包在归档文件(zip / jar / war)中,或者应用程序是否已取消归档到部署中的文件中环境。

To avoid deployment issues, I write some code to 'discover' the path by trying getResourceAsStream until a non-null inputStream is returned. 为避免部署问题,我尝试通过getResourceAsStream编写一些代码来“发现”路径,直到返回非null inputStream为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM