0

In my project I access the folder that is in /src/main/ressources/Mylib in eclipse it works well without any problem, but when i export the project into .jar file it does not work.

The line of code that bug:

File fi = new File(Testp.class.getClassLoader().getResource("Mylib/").getFile());

and it gives this bug:

Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:61)
Caused by: java.lang.NullPointerException
    at com.myproject.Testp.main(Testp.java:73)
    ... 5 more
Afatsum
  • 127
  • 1
  • 3
  • 11
  • Maybe this can help? https://stackoverflow.com/a/20389418/3154883 – Brother Oct 18 '19 at 13:49
  • The `getFile()` method of URL *does not* return a valid filename. It just returns the path portion of a URL, with all of its escapes of special characters. The method name is like that because 25 years ago when the URL class was created, most URLs actually referred to physical files, either local or remote. – VGR Oct 18 '19 at 14:47
  • use `getResourceAsStream()` – RobOhRob Oct 18 '19 at 14:52

1 Answers1

0

So you want to get all the files in a classpath resource folder? I found this example:

private static File[] getResourceFolderFiles (String folder) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL url = loader.getResource(folder);
    String path = url.getPath();
    return new File(path).listFiles();
}

I tested it with System.out.println(Arrays.toString(getResourceFolderFiles("foldername/"))); and it works. But your folder has to be on classpath!

bkis
  • 2,530
  • 1
  • 17
  • 31
  • my problem is this line (to get files from `resource` folder) `File fi = new File(Testp.class.getClassLoader().getResource("Mylib/").getFile());` work fine in eclipse, but when I export the projet to jar it doesn't work, – Afatsum Oct 18 '19 at 13:38
  • @Afatsum That *could* mean the folder is not really on your classpath. Try right-clicking it and then click `Build Path` -> `Add to Build Path`. – bkis Oct 18 '19 at 14:30