0

I have a maven project in Eclipse. Under the src/main/resources I have a directory named "directoryToCopy" containing files. Once I run my project, I want to copy "directoryToCopy" under a local directory "localDirec" in my desktop.

I used this :

File localDirec = new File("c:/desktop/scripts");
URI urlDir = ClassLoader.getSystemResource("directoryToCopy").toURI();
File srcDir = new File(urlDir.getPath());
FileUtils.copyDirectory(srcDir, localDirec);

This works fine locally, but when I want to run it as an executable jar file I get NullPointerException

Exception in thread "main" java.lang.NullPointerException
        at java.base/java.io.File.<init>(File.java:278)

Any suggestion please?

LSoft
  • 117
  • 1
  • 9
  • Have you tried opening your jar to see if the directoryToCopy stills falling under src/main/resources?? If it works in IDE then possibly some mistake while building your jar – Sabareesh Muralidharan Jun 25 '20 at 09:26
  • When I open my jar, I directly find my file directoryToCopy under it. There is no src/main/resources under an executable jar – LSoft Jun 25 '20 at 09:29
  • Possibly you might wanna see this, https://stackoverflow.com/a/13292358/10416835 – Sabareesh Muralidharan Jun 25 '20 at 09:33
  • I have tried both getClass().getResource() and getClass().getClassLoader().getResource(), same issue, nullPointerException – LSoft Jun 25 '20 at 09:41

1 Answers1

0

You can always, try printing the path

System.out.println(getClass().getResource(getClass().getSimpleName() + ".class"));

Class's getResource() - documentation states the difference:

"This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource."

Use / when path should not be changed, try printing the loaded path, it would make things clear.

  • I tried to print the paths : For the URI : jar:file:/C:/Users/Myproject/target/Myproject-0.0.1-jar-with-dependencies.jar!/directoryToCopy, but I can't print the file path because right there i get the nullpointer exception. – LSoft Jun 25 '20 at 10:31
  • Have you tried using getClass().getClassLoader().getResource(/directoryToCopy)?? – Sabareesh Muralidharan Jun 25 '20 at 10:36
  • Yes, I added /directoryToCopy but I get null in the print, I tried Myclass.class.getClassLoader().getResource(directoryToCopy) it gives me the exact path as ClassLoader.getSystemResource(directoryToCopy) – LSoft Jun 25 '20 at 10:55