1
votes

I am trying to get a JSON file form my resource folder in the main method using relative path. The code works using absolute path but this breaks once I build a jar file from my project which is want I want.

public static void main(String[] args) throws FileNotFoundException {
// Read in database
db = Database.read(Thread.currentThread().getContextClassLoader().getResource("JSON/inhabitants.json").toExternalForm());
names = db.getAllNames();

Read calls a method in Database which uses a inputstream to read the file.

  public static Database read(String filename) throws FileNotFoundException {
    InputStream is = new FileInputStream(filename);
    Reader reader = new InputStreamReader(is);

    return gson.fromJson(reader, Database.class);
  }

The error I am getting is the following :

java.io.FileNotFoundException: file:/Users/timpelser/IdeaProjects/TurfApp/target/classes/JSON/inhabitants.json (No such file or directory) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.(FileInputStream.java:138) at java.io.FileInputStream.(FileInputStream.java:93) at Core.Database.read(Database.java:22) at Main.main(Main.java:51) ... 11 more

The file in directory /Users/timpelser/IdeaProjects/TurfApp/target/classes/JSON/inhabitants.json

does exist however so I have no idea what is going wrong.

Here is my folder structure (Maven basic structure):

folder structure

Is there a solution which will still able me to deploy it as a jar file ?

EDIT (25/09) : If I use getResourceAsStream instead of getResource, I am getting the following error :

Caused by: java.io.FileNotFoundException: java.io.BufferedInputStream@4f8e5cde (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at Core.Database.read(Database.java:22)
at Main.main(Main.java:51)
... 11 more
2
Just for information, why are you putting json file in target folder? Target is build folder, and will be erased every time you do mvn cleanamicoderozer
I did not do that on purpose, I just added the file to the resource folder and when building the artifacts it added it to the targets folderTim Pelser

2 Answers

1
votes

You have to use getResourceAsStream to read files from within the running jar (which contains the files within src\main\resources)!

0
votes

Use This,

Resource resource = new classpathResource(json);

new ObjectMapper.readValue(resource.getInputStream(),Object.class);