Reputation: 129
I've created an app on Android Studio with Libgdx that can read a .json file that is stored in the project folder
it goes like this
private void readFile() {
JsonParser jsonParser = new JsonParser();
try (FileReader reader = new FileReader("file.json"))
{
//reads file
} catch (IOException | ParserException e) {
e.printStackTrace();
}
}
Everything works on the desktop application, but when I run it on android app ofcourse its not there and it doesn't load. I can't find any information to where it has to be stored. FileReader only lets me input a string, but not the location where the file is.
Is FileReader a bad choice or the location where it is looking can be changed?
Upvotes: 4
Views: 5810
Reputation: 1420
You need to store you json file in assets folder. And to read your .json from assets file use below code.
JSONObject obj = new JSONObject(readJSONFromAsset());
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("yourFile.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Upvotes: 3