Using JSON File in Android App Resources

前端 未结 8 1173
盖世英雄少女心
盖世英雄少女心 2020-11-28 21:00

Suppose I have a file with JSON contents in the raw resources folder in my app. How can I read this into the app, so that I can parse the JSON?

8条回答
  •  迷失自我
    2020-11-28 21:12

    See openRawResource. Something like this should work:

    InputStream is = getResources().openRawResource(R.raw.json_file);
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        is.close();
    }
    
    String jsonString = writer.toString();
    

提交回复
热议问题