gpt4 book ai didi

java - 如何缓存/读取json文件?

转载 作者:行者123 更新时间:2023-12-02 01:31:48 25 4
gpt4 key购买 nike

我在尝试缓存和读取 json 文件时遇到问题,我使用 google dev 的示例来缓存文件,然后尝试使用不同的函数 readCache(),但我在

上收到错误

outputStream.read() -> cannot resolve method 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");
}

关于java - 如何缓存/读取json文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55926354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com