Java 9.0 | ClassLoader :: getResourceAsStream: NullPointerException exception

This code snippet below, where I get the file from the folder inside the "/ resource" folder, works fine for me in Java 8:

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

In Java 9, this is not so, classLoader.getResourceAsStream (file_name) returns null:

 java.lang.NullPointerException: source 

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

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

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

  • What's happening?
  • How to fix it?

Here is my project structure :

enter image description here

*. jar Output structure:

 *.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 - .. 
+5
source share
1 answer

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

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

Now you can access this folder.

HOW TO ACCESS RESOURCES FROM ANOTHER CLASS

  • Inside the resources_module package, create an empty class
  • From another class (including other modules), to get an InputStream , you must call the class you created earlier (an empty class), for example:

    (Your empty class).class.getResourceAsStream(path);

+1
source

Source: https://habr.com/ru/post/1273817/


All Articles