1

我正在使用 url 来获取文件进行解析。现在我想读取 sdcard 中的文件进行解析。我该怎么做?这是我的代码

从 url 读取文件

    private static String url = "http://10.0.2.2/device1.json";
    JSONObject  json = jParser.getJSONFromUrl(url);
            devices = json.getJSONArray(TAG_DEVICES);

现在我想通过读取 sdcard 中的文件来做到这一点

    java.io.File device = new java.io.File("/mnt/sdcard/device1.json");
    FileReader device_Fr = new FileReader(device);

接下来如何传递这个文件进行解析?

4

2 回答 2

1

使用此代码

将文件中的数据读入字符串并将其传递给 JSONObject。

BufferedReader reader = new BufferedReader(new FileReader(filePath));
    String line, results = "";
    while( ( line = reader.readLine() ) != null)
    {
        results += line;
    }
    reader.close();


JSONObject obj = new JSONObject(results);
于 2012-08-29T07:24:37.163 回答
0

一种方法是读取 json 并将其存储在字符串中。然后像这样解析它:

   String jsonStr = // read from file
    JSONObject  json = new JSONObject( jsonStr);
    // parse
 

  devices = json.getJSONArray(TAG_DEVICES);
于 2012-08-29T07:24:10.133 回答