【问题标题】:How to assign File to InputStream?如何将文件分配给 InputStream?
【发布时间】:2018-05-08 16:56:47
【问题描述】:

之前我从android resourcesraw文件夹中读取了一个json文件,

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 现在为空。请纠正我

错误日志是,

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

【问题讨论】:

  • /folder 不是传递给 getExternalFilesDir() 的参数的有效值。除此之外,“这没有按我的预期工作”是什么意思?你有什么症状?
  • @CommonsWare 详细说明了我的问题。请立即查看
  • 同样,/folder 不是getExternalFilesDir() 的有效值。您要加载的文件在哪里?
  • 来自我设备的外部存储(“Android/data/myappfolder”)
  • 但我使用了 File fileJson = new File(getActivity().getExternalFilesDir("/folderName"), "jsonfile.json"); fileJson .createNewFile();创建该文件

标签: android fileinputstream


【解决方案1】:

第 1 步:将文件放入您认为是 Android/data/myappfolder/files/ 的位置。因此,您将拥有Android/data/myappfolder/files/jsonfile.json

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

【讨论】:

    猜你喜欢
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多