为什么getResource返回null [英] Why does getResource return null

查看:291
本文介绍了为什么getResource返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问项目中的文件。但是getResource方法返回null。

I'm trying to access a file in my project. But getResource method returns null.

这就是我的项目的样子:

This is how my project looks like:

Thread.currentThread().getContextClassLoader().getResource("assets/xxx.png"); //returns null

eclipse工作区中的项目文件夹如何:

And how project folder in eclipse workspace looks like:

为什么呢?我想访问我的资源文件夹中的文件?

Why? I want to access files in my assets folder?

编辑
我创建了一个jar文件,这是jar的内容:

Edit I created a jar file and this is content of the jar:

解决了

首先,我有很多图片文件,所以我想整理一下他们都在一个文件夹中。我将assets文件夹放在src目录中,最后我能够访问这些文件。

First of all, I've a lot of image files so I want to organize all them in a folder. I put the assets folder in src directory and finally I was able to access the files.

this.getClass().getClassLoader().getResource("assets/xxx.png");

推荐答案

有很多方法可以将资源添加到jar文件中,你可以把它放在src中,如果你使用maven,ant等添加为资源...如果你能够捆绑整个目录,那么你应该能够使用你原来的一段代码。
使用当前结构,您可以使用以下代码。

There are lot of ways to add a resource to the jar file, you can put it in src, add as a resource if you use maven, ant etc... If you able to bundle whole directory then you should be able to use your original piece of code. With the current structure you can use following piece of code.

Thread.currentThread().getContextClassLoader().getResource("/xxx.png"). 

这篇关于为什么getResource返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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