从内部存储读取JSON文件的内容 [英] Read content of JSON File from Internal Storage
本文介绍了从内部存储读取JSON文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从内部存储输出JSON文件的内容?以下是当前正在处理的内容.
How can I output the content of a JSON file from Internal Storage? The following is what am currently working on.
String filename = "names.json";
final File file = new File(Environment.getDataDirectory(), filename);
Log.d(TAG, String.valueOf(file));
日志显示为:/data/names.json
names.json
[
"names",
{
"name": "John Doe"
}
]
推荐答案
从文件中读取字符串并将其转换为JsonObject
或JsonArray
Read string from file and convert it to JsonObject
or JsonArray
String jsongString = readFromFile();
JSONArray jarray = new JSONArray(str);
使用以下方法从内部存储文件读取数据并以String
的形式返回.
Use below method to read data from internal storage file and return as String
.
private String readFromFile() {
String ret = "";
InputStream inputStream = null;
try {
inputStream = openFileInput("names.json");
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);
}
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());
}
finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
这篇关于从内部存储读取JSON文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文