How can I read a resource file in an unexploded war file deployed in Tomcat?

你说的曾经没有我的故事 提交于 2019-12-10 15:29:31

问题


I am trying to load a binary image file to do some processing inside my server-side Java code. I am currently placing my image in the package where my executing class exists and calling:

Image img = Image.getInstance(this.getClass().getResource("logo.png"));

This works fine when I'm running Tomcat on my development box in an exploded war setup, but when I deploy to a server running Tomcat where it doesn't explode war files, the call to getResource returns null.

I've also tried moving the image to my context root and accessing it like this:

Image img = Image.getInstance(this.getClass().getResource("/../../logo.png"));

Again, this works on my development box, but not when I deploy it elsewhere.

Is there a better way to access this file? What am I doing wrong?

Thanks!!


回答1:


If you are building using Maven, you'll want to make sure the image actually gets placed into the archive.

Put resources in your src/main/resources directory. Then access them with:

this.getClass().getResource("/logo.png"); 

or:

Thread.currentThread().getContextClassLoader().getResource("logo.png"); 

(Code samples from comment above, but put in the answer to be more visible)




回答2:


You could put your images at the root of your classpath and try this:

Thread.currentThread().getContextClassLoader()
               .getResource("logo.png");


来源:https://stackoverflow.com/questions/8762901/how-can-i-read-a-resource-file-in-an-unexploded-war-file-deployed-in-tomcat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!