简体   繁体   English

getResourceAsStream 返回具有正确路径的 null

[英]getResourceAsStream returns null with correct path

my piece of code:我的一段代码:

private InputStream assetFromJAR(String fileName) {
    return getClass().getResourceAsStream("/view/assets/ims/" + fileName + ".png");
}

returns always null...总是返回空...

My structure is:我的结构是:

src
  main
   java  <- source root
     view
       assets
         ims

it does not make sence why is this happening, path is correct so why does it always return null?它没有意义为什么会发生这种情况,路径是正确的那么为什么它总是返回 null?

Thanks for answers!感谢您的回答!

Maven java projects are structured in way to separate the *.java files and resource files(like *.properties, *.jpg, *.png, etc..) Maven java 项目的结构将 *.java 文件和资源文件(如 *.properties、*.jpg、*.png 等)分开

  • For *.java files: src/main/java folder对于 *.java 文件:src/main/java 文件夹
  • For resources: src/main/resources对于资源:src/main/resources

So place your resources files directly under "src/main/resources" or sub folder of resources directory(like "src/main/resources/view/assets/ims/" for your project).因此,将资源文件直接放在“src/main/resources”或资源目录的子文件夹下(如项目的“src/main/resources/view/assets/ims/”)。

Then you can easily access the resource files.然后你就可以轻松访问资源文件了。

private InputStream assetFromJAR(String fileName) {
     return getClass().getResourceAsStream("/view/assets/ims/" + fileName + ".png");
}

I'm going to start with some things that are obvious, because you haven't indicated what you've tried.我将从一些显而易见的事情开始,因为您没有说明您尝试过的内容。 I apologize if you've done, or are aware of this:如果您已经完成或意识到这一点,我深表歉意:

Paths that begin with "/" are found somewhere in the class path.以“/”开头的路径位于类路径中的某处。 Paths without the beginning "/", start from where the code is called.不以“/”开头的路径,从调用代码的地方开始。 Your class path roots may not be what you think they are, or the.png file is not being moved from your source directory to your target directory.您的类路径根可能不是您认为的那样,或者 .png 文件没有从您的源目录移动到目标目录。

Have you verified the file is in the target directory ( assuming your using maven for building), or wherever your.class files end up?您是否已验证该文件位于目标目录中(假设您使用 Maven 进行构建),或者您的 .class 文件位于何处?

Have you verified what you're class path roots are?您是否已验证您的类路径根是什么?

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

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