簡體   English   中英

如何緩存/讀取json文件?

[英]How to cache/read a json file?

我在嘗試緩存和讀取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();
    }
}

嘗試將您的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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM