猿问

如何缓存/读取 json 文件?

我在尝试缓存和读取 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();

    }

}


慕无忌1623718
浏览 177回答 1
1回答

森栏

尝试将您的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");}
随时随地看视频慕课网APP

相关分类

Java
我要回答