如何将文件分配给InputStream?

时间:2018-05-08 16:56:48

标签: android fileinputstream

以前我从android raw的{​​{1}}文件夹中读取了一个json文件,

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
        }

但现在File fileJson = new File(getActivity().getExternalFilesDir("/folderName"), "jsonfile.json"); InputStream inputStream = null; try { inputStream = new FileInputStream(fileJson); } catch (FileNotFoundException e) { e.printStackTrace(); } 为空。请纠正我

错误日志是,

responseData

1 个答案:

答案 0 :(得分:1)

步骤1:将文件放在您认为的Android/data/myappfolder/files/中。因此,您将拥有Android/data/myappfolder/files/jsonfile.json

第2步:使用File fileJson = new File(getActivity().getExternalFilesDir(null), "jsonfile.json");