本文介绍了将json数据写入并读取到内部存储android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个从php收到的json数组
I have a json array received from php
[
{
"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数组
可以进一步编辑。 - What i want is to write this data in a
file_name.anyextension
inmy apps data folder or anywhere safe. - Also read this data from
file_name.anyextension
and convert it to avalidjson array
that can be further edited.
任何人都可以告诉我一个方法我怎么可能这件事?
Can anyone show me a way how can i possibly to this thing ?
推荐答案
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
When read string from file convert it to JsonObject or JsonArray
JSONArray jarray = new JSONArray(str);
这篇关于将json数据写入并读取到内部存储android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!