How can I output the content of a JSON file from Internal Storage? The following is what am currently working on.
String filename = "names.json";
final File file = new File(Environment.getDataDirectory(), filename);
Log.d(TAG, String.valueOf(file));
The log shows as: /data/names.json
names.json
[
"names",
{
"name": "John Doe"
}
]
Read string from file and convert it to JsonObject
or JsonArray
String jsongString = readFromFile();
JSONArray jarray = new JSONArray(str);
Use below method to read data from internal storage file and return as String
.
private String readFromFile() {
String ret = "";
InputStream inputStream = null;
try {
inputStream = openFileInput("names.json");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With