0

i'm working on a little project and i need to move a file from the application JAR to another location outside the JAR.

This is how my JAR file looks like:

MyApp.JAR
   |- META-INF
       |- MANIFEST.MF
   |- files
       |- myFile.exe
   |- MainClass.class

What i'd like to do is move myFile.exe to C:\\ (for example). So in the MainClass i tried with:

23. Path path = Paths.get(getClass().getClassLoader().getResource("/files/myFile.exe").toURI());
24. byte[] bytes = Files.readAllBytes(path);

25. FileOutputStream fos = new FileOutputStream("C:\\myFile.exe");
26. fos.write(b);
27. fos.close();

After running my application i get a NullPointerException, here's it:

java.lang.NullPointerException
    at MainClass.<init>(MainClass.java:23)
    at MainClass.main(MainClass.java:66)

(Line 66 is where i call the constructor with new MainClass();)

I know the NPE is probably thrown because myFile.exe cannot be found, but i can't figure out why... When i open the JAR i can see the files folder with the exe inside. Maybe i'm accessing the file in a wrong way? I tried many other ways that i found here on StackOverflow but nothing works...

Thanks in advance and sorry for my english.

Marcello Davi
  • 433
  • 4
  • 16
  • Maybe you can split line 23 into multiple assignments line-by-line, that way it will be visible what returns `null`? – randers Dec 19 '15 at 17:20
  • The correct path is `files/myFile.exe`, without leading slash. But you should just read bytes from the InputStream returned by `getClass().getClassLoader().getResourceAsStream("files/myFile.exe")` – JB Nizet Dec 19 '15 at 17:21

2 Answers2

0

I think here you are taking too many intermediate clunky steps, because the standard Java APIs don't allow you to do it immediately. I recommend you using IOUtils.copy to copy the bytes over:

try(InputStream resourceStream = getClass().getResourceAsStream("/files/myFile.exe");
    FileOutputStream fos = new FileOutputStream("C:\\myFile.exe"))
{
    IOUtils.copy(resourceStream, fos);
} // optionally, catch IOException here (or declare it to be thrown)

If you need assistance with the URL provided to getResourceAsStream(), look here.

Community
  • 1
  • 1
randers
  • 5,031
  • 5
  • 37
  • 64
0

You are using an absolute path: you should be using ("files/myFiles.exe") iso ("/files/myFiles.exe")

ruben056
  • 112
  • 8