从内部存储中读取JSON文件的内容

时间:2016-11-08 09:45:26

标签: android json

如何从内部存储输出JSON文件的内容?以下是我目前正在进行的工作。

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"
  }
]

2 个答案:

答案 0 :(得分:4)

从文件中读取字符串并将其转换为JsonObjectJsonArray

String jsongString = readFromFile();
JSONArray jarray = new JSONArray(str);

使用以下方法从内部存储文件中读取数据并返回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;
}

答案 1 :(得分:2)

将您的json文件添加到res / raw / generated.json

并在您的活动中访问像这样的json数据

InputStream is = getResources().openRawResource(R.raw.generated);
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
        Reader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        int n;
        try {
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String jsonString = writer.toString();
    Log.d("jsonString",jsonString);