如何缓存/读取json文件?

时间:2019-04-30 17:53:32

标签: java android json caching

我在尝试缓存和读取json文件时遇到问题,我使用了来自Google dev的示例来缓存文件,然后我尝试使用其他功能username = "MrShaun" filename = "C:\\Users\\{0}\\Desktop\\PC info.txt".format(username) file = open(filename, 'w') 来读取文件,但是

出现错误
  

outputStream.read()->无法解析方法read().....

有人可以告诉我我在做什么错吗?

readCache()

1 个答案:

答案 0 :(得分:2)

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