Java 9.0 | ClassLoader :: getResourceAsStream:NullPointerException [英] Java 9.0 | ClassLoader::getResourceAsStream: NullPointerException

查看:601
本文介绍了Java 9.0 | ClassLoader :: getResourceAsStream:NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的这段代码,我从 / resource 文件夹中的文件夹中获取文件,在Java 8中对我来说很好用:

This piece of code down below, where I take my file from folder which is inside the "/resource" folder, works fine for me in Java 8:

//e.g fileName = "folder0/file1.extension2"

ClassLoader classLoader = ResourceLoader.class.getClassLoader();
InputStream in = classLoader.getResourceAsStream(fileName);
Scanner scanner = new Scanner(in, "UTF-8");

在Java 9中没有, classLoader.getResourceAsStream(fileName)返回null:

In Java 9 it does not, classLoader.getResourceAsStream(fileName) returns null:

java.lang.NullPointerException: source

但是,如果我直接使用 / resource 文件夹中的文件,这样可以正常工作:

However, if I use files straight from "/resource" folder, this works fine:

fileName = "file0.extension1"; // It works!

我的问题很明显,说实话,有两个:

My question is quite obvious, to be honest, there are two of them:


  1. 发生了什么事?

  2. 如何修复?

这是我的项目结构

*。jar 输出结构:

*.jar:
- javaFolder1
    -javaFolder1.1
        -ResourceLoader.class
        -jclass1.1.2.class
        -jclass1.1.3.class
    -javaFolder1.2
- javaFolder2
    - ..
- ..

- unreachableResourceFolderImTryingToAccess1
    -resource1.1.ext
    -resource1.2.ext
- unreachableResourceFolderImTryingToAccess2
    - ..
- unreachableResourceFolderImTryingToAccess3
    - ..
-resource0.1.ext
-resource0.2.ext
- ..

- somedll1.dll
- somedll2.dll
- ..


推荐答案

e module_info.java文件,你必须打开文件,例如,包名,你在其中的文件是资源,如果那个包在另一个名为resources_module的内部,代码将是:

In the module_info.java file, you have to open the files, for example, the package name, in which you have the files is "resources" and, if that package is inside another called "resources_module" the code will be:

exports resources_module;
opens resources;
opens resources.(the name of another folder inside the package);

现在你可以访问该文件夹了。

And now you can access to that folder.

如何从另一个类访问资源


  1. 在resources_module包中创建一个空类

  2. 从另一个类(包括其他模块)获取 InputStream ,你必须调用之前创建的类(像这样的空类:

  1. Inside the package "resources_module" create a empty class
  2. From another class (including other modules), to get an InputStream you have to call the class you created before (the empty class) like this:

(你的空类).class.getResourceAsStream(path);

这篇关于Java 9.0 | ClassLoader :: getResourceAsStream:NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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