亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何緩存/讀取 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 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號