0
votes

I am trying to read a file from resource directory using below code

new FileInputStream(new File(getClass().getClassLoader().getResource(keyFile).getFile()))

getting below exception at runtime

java.io.FileNotFoundException: file:\D:\WorkSpace\server\target\server.jar!\BOOT-INF\classes!\config\key.pgp (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.(Unknown Source)

2
As it says: The filename, directory name, or volume label syntax is incorrect. Please check the syntax. If not, please share the code where keyFile variable is declareduser8616404
actually..the file exist when i checked inside the jar...value for keyfile is config\key.pgp....is there any different way to read the file from jarrocky
Option 1 in the answer I just posted should be able to read the file from the jar.John
@basky see the my answer below.Sagar P. Ghagare

2 Answers

3
votes

Depending on where the resource which you are trying to fetch is located within the jar, you should use relative path to fetch the resource. You can also skip the File object altogether by asking the resource directly as an InputStream with ResourceAsStream method:

InputStream in = getClass().getResourceAsStream("/config/key.pgp");
0
votes

From this:

java.io.FileNotFoundException: file:\D:\WorkSpace\server\target\ server.jar!

It looks like the code is running from inside a jar and is looking for the file in the jar.

A couple of options:

1.) Add the file to the jar where your .class files are and use the class path to get to the file (don't forget the leading /): /com/mycompany/myproject/files/myfile.txt

2.) Use an absolute path to the file: "D:\WorkSpace\server\target\BOOT-INF\classes\config\key.pgp"