Search code examples
androidfileinputstream

How to assign File to InputStream?


Previously I read a json file from raw folder of android resources,

InputStream inputStream = getResources().openRawResource(R.raw.jsonfile);

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        int ctr;
        try {
            ctr = inputStream.read();
            while (ctr != -1) {
                byteArrayOutputStream.write(ctr);
                ctr = inputStream.read();
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        JSONObject jObject = null;
        try {
            jObject = new JSONObject(
                    byteArrayOutputStream.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Gson g = new Gson();

        MyList responseData = g.fromJson(jObject.toString(), MyList.class);

        if (responseData.getPeopleList().size() == 0) {
            //do something
        }

Now I need to save that file in external storage of device. I tried instead of 1st line in above segment,

File fileJson = new File(getActivity().getExternalFilesDir("/folderName"), "jsonfile.json");

InputStream inputStream = null;
try {
    inputStream = new FileInputStream(fileJson);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

but now responseData is null now. Correct me please

error log is,

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

Solution

  • Step #1: Put the file in what you think is Android/data/myappfolder/files/. So, you will have Android/data/myappfolder/files/jsonfile.json.

    Step #2: Use File fileJson = new File(getActivity().getExternalFilesDir(null), "jsonfile.json");