Red Virus
Red Virus

Reputation: 1707

Read content of JSON File from Internal Storage

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"
  }
]

Upvotes: 4

Views: 9289

Answers (2)

Priyank Patel
Priyank Patel

Reputation: 12382

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;
}

Upvotes: 5

hasan_shaikh
hasan_shaikh

Reputation: 1480

Add your json file to res/raw/generated.json

and in your activity access the json data like this

InputStream is = getResources().openRawResource(R.raw.generated);
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
        Reader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        int n;
        try {
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String jsonString = writer.toString();
    Log.d("jsonString",jsonString);

Upvotes: 3

Related Questions