0

I want to build a json object using Gson from a json file received as parameter while executing the jar.

This is the method I used to read the json file

public static JsonObject loadData(String filename) throws FileNotFoundException {
        Gson parser = new Gson();
        File jsonFile = new File(filename);
        BufferedReader br = null;
        JsonObject fileParsed;
        try {
            br = new BufferedReader(new FileReader(jsonFile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            fileParsed = parser.fromJson(br, JsonObject.class);
        } catch (JsonSyntaxException e) {
            throw e;
        }
        return fileParsed;
    }

This method was working before generating the jar when I try to run it using the framework(IntelliJ or Eclipse) but If I generate a jar file and then I try to get the json file that is not inside the jar file is not working.

If I execute java -jar file.jar jsonFile.json I'm getting java.lang.NullPointerException

I tried some other ways but always NullPointerException. Any clue about this? Thanks!

Juan
  • 11
  • 2
  • Probably the current directory is different when you run the jar file and the JSON file is in a different directory. You get an NPE because you try to use `br` even if opening the file failed. This is wrong. You declare that the method throws `FileNotFoundException` but you consume any such exception you get, you don't throw it. But you can throw `JsonSyntaxException`. You also don't close the file. You should be using [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html). – David Conrad Feb 24 '22 at 15:44
  • The Jar file and the json file are in the same directory. Maybe I posted the code that after edited 200 times is not very well but the problem is not that the jar and the json file are in the same file. In all the ways I tried to open the file I get NullPointerException – Juan Feb 24 '22 at 16:20
  • It doesn't necessarily matter whether the jar file and the JSON file are in the same directory, what matters is what the OS and JVM's idea of the "current directory" is while the jar file is running. I just tried a stripped-down version of your code (just reading the first line of the file and returning it instead of parsing it as JSON) and it worked. You can check the current directory by one of the methods in [this question](https://stackoverflow.com/questions/4871051/how-to-get-the-current-working-directory-in-java). – David Conrad Feb 24 '22 at 16:43

0 Answers0