0

I'm using this code File serviceAccountFile = new File(Main.class.getResource("/serviceAccountKey.json").getFile()); to access a json file inside my "resources" folder. It works fine when I'm running it from intellij. But i get this error when running the program from the jar.

java.io.FileNotFoundException: file:\C:\Users\Ashirwada\Documents\IIT\JAVA\POS\target\POS-0.6-jar-with-dependencies.jar!\serviceAccountKey.json (The filename, directory name, or volume label syntax is incorrect)
        at java.base/java.io.FileInputStream.open0(Native Method)
        at java.base/java.io.FileInputStream.open(Unknown Source)
        at java.base/java.io.FileInputStream.<init>(Unknown Source)
        at ashirwada.pos.Firebase.initializeFirebase(Firebase.java:27)
        at ashirwada.pos.Main.init(Main.java:33)
        at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
        at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(Unknown Source)
        at java.base/java.lang.Thread.run(Unknown Source)

I have other files like fxml files and jpg inside my resource file. They get detected and runs fine. This json file is the only thing thats giving me problems. I opened the Jar with winrar and the json file is there with the rest of the fxml files and the jpg. I'm using maven to compile my jar with the dependencies i need.

3 Answers3

0

System cannot resolve file C:\Users\Ashirwada\Documents\IIT\JAVA\POS\target\POS-0.6-jar-with-dependencies.jar!\UI\serviceAccountKey.json due to the file is in jar file

You should extract the jar in to a folder and read json file from there

Or you can read file as a resource

InputStream in = etClass().getResourceAsStream("/UI/serviceAccountKey.json");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
Sann Tran
  • 159
  • 5
  • My fxml files are accessed using Parent root = FXMLLoader.load(getClass().getResource("/UI/Login.fxml")); and they work fine. I don't understand why only this doesn't work. – Ashirwada Wijerathna Aug 04 '18 at 16:15
  • 1
    I found this thread, may be help you https://stackoverflow.com/questions/20389255/reading-a-resource-file-from-within-jar – Sann Tran Aug 04 '18 at 16:32
0

That's because after you package your resource into a jar, the string you get by URL.getFile() would be invalid for the constructor File(String path).Use getResourceAsStream instead may solve your problem.

0

try this

File(Main.class.getClassLoader().getResource("/serviceAccountKey.json").getFile());
Keaz
  • 955
  • 1
  • 11
  • 21