Reputation: 83
I'm working on a simple app and im trying to understand how to read from a json file using a json parser. I wrote a simple json file and put it in one of my directories. Then I used right clock to get the path, and wrote the following code:
public void myParser() {
JSONParser parser = new JSONParser();
String path = "C:\\Users\\My Name\\IntelliJIDEAProjects\\Intereview\\app\\src\\main\\res\\Data\\dataStructures.json";
try{
JSONArray topics = (JSONArray)parser.parse(new FileReader(path));
for(int i=0;i<topics.length();i++) {
JSONObject object = topics.getJSONObject(i);
String title = object.optString("title").toString();
Log.i(TAG,title);
}
}
catch(JSONException e) {
Log.e("Internal Problem", e.getMessage());
} catch (ParseException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
from some reason, i get this error when running the app:
java.io.FileNotFoundException: C:\Users\My Name\IntelliJIDEAProjects\Intereview\app\src\main\res\Data\dataStructures.json: open failed: ENOENT (No such file or directory)
what could be the reason behind that? i've been working on this for the past few hours and I just can't figure it out.. Thanks
Upvotes: 0
Views: 3478
Reputation: 616
you need to put json inside the assets folder.
Upvotes: 0
Reputation: 1006614
You have android on this question, so I assume that you are trying to write an Android app. If so, this will not work:
String path = "C:\\Users\\My Name\\IntelliJIDEAProjects\\Intereview\\app\\src\\main\\res\\Data\\dataStructures.json";
My guess, based on that path, is that you are trying to package a JSON file with your app. In that case, you cannot create random directories under res/
either. Even if this JSON file were in a proper res/
directory (e.g., res/raw/
), you cannot access it via a FileReader
. It is a file on your development machine. It is not a file on the Android device.
Your two main options are:
Move that JSON file from res/Data/
into res/raw/
. Then, use getResources().openRawResource(R.raw.dataStructures)
to get an InputStream
on the JSON.
Move that JSON file from res/Data/
into assets/
. Then, use getAssets().open("dataStructures.json")
to get an InputStream
on the JSON.
Note that getResources()
and getAssets()
are methods on Context
and its subclasses, such as Activity
.
Upvotes: 1
Reputation: 1221
This appears when the file isn't there...
Check the spelling of your pathname (intereview?)
and... check if the file is there.
Upvotes: 0