如何缓存/读取JSON文件



我在尝试缓存和读取JSON文件时遇到问题,我使用Google Dev的示例来缓存文件,然后我尝试使用其他不同功能readCache(),但我在

上遇到了一个错误

outputStream.Read(( ->无法解析方法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();
    }
}

尝试将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");
}

最新更新