Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read content of JSON File from Internal Storage

Tags:

json

android

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"
  }
]
like image 239
Red Virus Avatar asked Feb 06 '23 18:02

Red Virus


1 Answers

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;
}
like image 119
Priyank Patel Avatar answered Feb 13 '23 07:02

Priyank Patel