Red Virus Red Virus - 25 days ago 10
Android Question

Read content of JSON File from Internal Storage

Every bigger in this and wanted to know how can I output the content of a json file from Internal Storage. The following is what am currently working it.

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

Answer

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 and from internal storage file return as String.

private String readFromFile() {

    String ret = "";

    try {
        InputStream 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);
            }

            inputStream.close();
            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());
    }

    return ret;
}
Comments