0

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)

rocky
  • 753
  • 2
  • 10
  • 26
  • 1
    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 declared –  Dec 28 '18 at 12:02
  • 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 jar – rocky Dec 28 '18 at 12:07
  • Option 1 in the answer I just posted should be able to read the file from the jar. – John Dec 28 '18 at 12:11
  • @basky see the my answer below. – Sagar P. Ghagare Dec 28 '18 at 13:09

2 Answers2

3

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");
pnkkr
  • 337
  • 3
  • 15
  • Upvoted but one should mention that `File` and `FileInputStream` are for the physical file system, not resource "files" on the class path, possibly inside a jar. – Joop Eggen Dec 28 '18 at 13:02
0

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"

John
  • 3,458
  • 4
  • 33
  • 54
  • did you try something like getClass().getClassLoader().getResource("/config/key.pgp") – John Dec 28 '18 at 12:55