java getResource() 不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12440035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java getResource() not working
提问by sakis kaliakoudas
this is driving me crazy. I have a NetBeans project in a folder with the following structure:
这真让我抓狂。我在具有以下结构的文件夹中有一个 NetBeans 项目:
MyProject
---- build
---- src
---- resources
in src my code is in packages. What I am trying to do is to use
在 src 我的代码在包中。我想做的是使用
getClass().getResource("/resources/new.png");
from a class in package com.my.package but it just refuses to work! The "new.png" image is in the resources folder. Am I missing something here?
来自包 com.my.package 中的一个类,但它只是拒绝工作!“new.png”图像位于资源文件夹中。我在这里错过了什么吗?
After a lot of playing around and moving the "new.png" image here and there to see when it will find the image, it finally worked but only when I put the image in the build folder. So what do I have to do to make this work ?
经过大量玩耍并四处移动“new.png”图像以查看它何时会找到图像后,它终于起作用了,但只有当我将图像放入构建文件夹时。那么我该怎么做才能完成这项工作?
edit: sorry, wrong String in method parameter. Corrected now
编辑:抱歉,方法参数中的字符串错误。现在更正
采纳答案by DNA
I'm not familiar with NetBeans, but the problem is probably that the resources
folder (or the root of the project, for that matter) is not on the classpath, unlike build
.
我不熟悉 NetBeans,但问题可能是resources
文件夹(或项目的根,就此而言)不在类路径上,与build
.
You need to configure NetBeans to add the root folder, or resources
to the classpath, and load the file relative to there.
您需要配置 NetBeans 以添加根文件夹或resources
类路径,并加载相对于那里的文件。
See also this question: Java - getClassLoader().getResource() driving me bonkers
回答by S. Esteves
This works fine:
这工作正常:
BufferedImage image = ImageIO.read(getClass().getClassLoader().getResourceAsStream("file_name"));