简体   繁体   English

如何从SD卡读取json文件

[英]How can I read json file from SD Card

I need to read a json file from the SD card and display the data in the spinner. 我需要从SD卡读取一个json文件并在微调器中显示数据。 Is there any way to read the data from file in Android and display the contents of that file in spinner? 有没有办法从Android中的文件读取数据并在微调器中显示该文件的内容?

First read the file from SD card and then parse that file 首先从SD卡读取文件,然后解析该文件

Step-1 Retrieve the data from file from SD card. 步骤1从SD卡中检索文件中的数据。 see tutorial 教程

Step-2 Parse the data. 步骤2解析数据。 See How to parse JSON String 请参见如何解析JSON字符串

Sample code 示例代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM