简体   繁体   English

java getResource() 不工作

[英]java getResource() not working

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.在 src 中,我的代码在包中。 What I am trying to do is to use我想做的是使用

getClass().getResource("/resources/new.png"); 

from a class in package com.my.package but it just refuses to work.来自 class in package com.my.package 但它只是拒绝工作。 The "new.png" image is in the resources folder? “new.png”图像在资源文件夹中? Am I missing something here?我在这里错过了什么吗?

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.经过大量的尝试并将“new.png”图像移动到这里和那里以查看它何时会找到该图像,它终于起作用了,但只有当我将图像放入构建文件夹时。 So what do I have to do to make this work?那么我必须做些什么才能使这项工作?

edit: sorry, wrong String in method parameter.编辑:抱歉,方法参数中的字符串错误。 Corrected now现在更正

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 另见这个问题: Java - getClassLoader()。getResource()驱使我疯狂

这很好用:

BufferedImage image = ImageIO.read(getClass().getClassLoader().getResourceAsStream("file_name"));

look out with ImageIO.read(getClass().getClassLoader().getResourceAsStream("file_name"));看看ImageIO.read(getClass().getClassLoader().getResourceAsStream("file_name"));

...on windows you will get a URL encoded string, with %20 for spaces, so if you want to use that path to load a file, first call pathString.replace("%20", " ")...that $hice just nailed me in live! ...在 windows 上你会得到一个 URL 编码的字符串,其中 %20 为空格,所以如果你想使用该路径加载文件,首先调用 pathString.replace("%20", " ")... $hice 刚刚把我钉在了现场!

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

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