5

我需要从 SD 卡中读取一个 json 文件并在微调器中显示数据。有没有办法从Android中的文件中读取数据并在微调器中显示该文件的内容?

4

1 回答 1

17

首先从 SD 卡中读取文件,然后解析该文件

步骤 1 从 SD 卡中的文件中检索数据。看教程

步骤 2 解析数据。请参阅如何解析 JSON 字符串

示例代码

try {

            File dir = Environment.getExternalStorageDirectory();
            File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
            FileInputStream stream = new FileInputStream(yourFile);
            String jString = null;
            try {
                FileChannel fc = stream.getChannel();
                MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
                /* Instead of using default, pass in a decoder. */
                jString = Charset.defaultCharset().decode(bb).toString();
              }
              finally {
                stream.close();
              }


                    JSONObject jObject = new JSONObject(jString); 



        } catch (Exception e) {e.printStackTrace();}
于 2011-12-14T05:32:51.703 回答