简体   繁体   中英

NullPointerException on ClassLoader.getResource()

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.

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 .

您使用的是绝对路径:您应该使用("files/myFiles.exe") iso ("/files/myFiles.exe")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM