如何从SD卡中读取JSON文件

5

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

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();}

根据Android文档,它指出getChannel()在内存方面是昂贵的。有没有一种不使用通道的方法来完成这个操作? - Todd Painton
尽管映射文件的设置可能很耗费时间,但与流I/O相比,总体收益(在速度方面)是显著的。 - intrepidis
无法工作。 一些字符很奇怪? - Bulma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接