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 
3
  • Maybe this can help? stackoverflow.com/a/20389418/3154883 Commented Oct 18, 2019 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. Commented Oct 18, 2019 at 14:47
  • use getResourceAsStream() Commented Oct 18, 2019 at 14:52

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

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 That could mean the folder is not really on your classpath. Try right-clicking it and then click Build Path -> Add to Build Path.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.