L
L
Lordao2018-10-17 21:27:27
Java
Lordao, 2018-10-17 21:27:27

How to fix NPE error when running program as jar?

This is how I pull the json file from the resources. If you run the program through the studio, then everything starts without errors.

File file = new File(getClass().getResource("questions.json").getFile());
questions = gson.fromJson(new FileReader(file), Question[].class);

But when I build the project with Maven, I get the error java.io.FileNotFoundException: file:/home/ann/IdeaProjects/Testing/target/testing-1.0.jar!/questions.json (No such file or directory)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Cheypnow, 2018-10-18
@Lordao

Use getClass(). getResourceAsStream("questions.json")
You will receive InputStream, and further work with it as it is necessary. So it seems that the absolute path will not be used

E
Evhen, 2018-10-18
@EugeneP2

.getResource(" / questions.json").

L
Lordao, 2018-10-18
@Lordao

Solved the problem this way:

InputStream file = this.getClass().getClassLoader().getResourceAsStream(("questions.json"));
String json = IOUtils.toString(file, "UTF-8");
questions = new Gson().fromJson(json, Question[].class);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question