为了账号安全,请及时绑定邮箱和手机立即绑定

如何缓存/读取 json 文件?

如何缓存/读取 json 文件?

慕无忌1623718 2022-11-02 15:14:32
我在尝试缓存和读取 json 文件时遇到问题,我使用 google dev 的示例缓存文件,然后尝试使用不同的函数读取文件readCache(),但出现错误outputStream.read() -> 无法解析方法 read().....有人可以解释一下我在做什么错吗?private void cacheFile(JSONObject response) {     JSONObject res  = response;     String filename = "jsonfile";     FileOutputStream outputStream;     try {         outputStream = openFileOutput(filename, Context.MODE_PRIVATE);         outputStream.write(res.toString().getBytes("utf-8"));         outputStream.close();         Log.e(TAG, "Success");     } catch (Exception e) {         e.printStackTrace();     }}private void readCache(String filename) {    FileOutputStream outputStream;    try {        outputStream = openFileOutput(filename, Context.MODE_PRIVATE);        outputStream.read();        outputStream.close();    } catch (Exception e) {        e.printStackTrace();    }}
查看完整描述

1 回答

?
森栏

TA贡献1810条经验 获得超5个赞

尝试将您的readCache()方法更改为


private void readCache(String filename) {

    FileInputStream inputStream;

    try {

        inputStream = openFileInput(filename);

        String body = inputStreamToString(inputStream);

        inputStream.close();

    } catch (Exception e) {

        e.printStackTrace();

    }

}


private String inputStreamToString(InputStream inputStream) throws Exception {

    ByteArrayOutputStream result = new ByteArrayOutputStream();

    byte[] buffer = new byte[1024];

    int length;

    while ((length = inputStream.read(buffer)) != -1) {

        result.write(buffer, 0, length);

    }

    return result.toString("UTF-8");

}


查看完整回答
反对 回复 2022-11-02
  • 1 回答
  • 0 关注
  • 176 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号