将json数据写入和读取到内部存储Android
我从php收到一个json数组
[ {
"name":"Daniel Bryan",
"img":"pictures\/smallest\/dierdrepic.jpg",
"username":"@dbryan",
"user_id":"4"
},
{
"name":"Devil Hacker",
"img":"pictures\/smallest\/belitapic.jpg",
"username":"@dvHack",
"user_id":"1"
}
]
- 我想要的是将此数据 写入
file_name.anyextension
我的应用程序数据文件夹中或安全的任何位置。 - 还要从中读取此数据
file_name.anyextension
并将其转换为json array
可以进一步编辑的有效数据。
谁能告诉我一种方法我怎么可能做这件事?
回答:
private void writeToFile(String data) { try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = context.openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
从文件中读取字符串时,将其转换为JsonObject或JsonArray
JSONArray jarray = new JSONArray(str);
以上是 将json数据写入和读取到内部存储Android 的全部内容, 来源链接: utcz.com/qa/411630.html