1

I am new to ANT and having some trouble handling static files which I need to read via my Java code. I have the following structure:

build main example resository SomeClass.class data data.json src example repository SomeClass.java test 

In SomeClass.java I need to read the data.json file but I am getting error in resolving path. I think its related to ant somehow.

public class SomeClass { class SomeClass extends ArrayList<Quote> {} public Quote[] all() { String path = "../../../data/data.json"; Gson gson = new Gson(); try { BufferedReader br = new BufferedReader(new FileReader(path)); return gson.fromJson(br, Quote[].class); } catch (IOException e) { e.printStackTrace(); } return new Quote[]{}; } } 

I am getting the following error:

java.io.FileNotFoundException: 

I think since ant it putting the files in build folder hence I may need to put my files somewhere there too, I have tried that too but I think I need some more help.

1 Answer 1

1

A relative path is calculated relative from the execution directory. If you execute ant in the project root, then the relative path from there is data/data.json, not ../../../data/data.json.

When getting "File not found" errors, it's good to verify the execution directory, either in a debugger, or by inserting a print statement, for example:

System.out.println(new File(".").getAbsolutePath()); 

From the output, you will know faire and square in which directory the process is running in, and you will be able to calculate the correct relative path.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't know how many hours of life I have wasted finding this, why java has to do this to me.
Just one more thing, in production I would like to ship everything in a single file, can I somehow put my data file in the build folder and reference it from there?
That will depend on the execution directory of the process that will run your program.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.