从sdcard读取.xml文件

时间:2012-02-13 12:23:39

标签: android xml xml-parsing

我有一个名为bkup.xml的xml文件存储在sdcard" /sdcard/bkup.xml"。

为了创建bkup.xml,我使用了xmlSerialization。

我想从该bkup.xml文件中检索数据。

我见过很多例子,但几乎大多数都是使用资源文件并使用URL作为资源。但是没有人能给出sdcard文件的路径。

我不知道如何从该文件中获取数据并解析它。

提前致谢。

任何建议都将受到赞赏

2 个答案:

答案 0 :(得分:5)

Here是一个完整的源代码示例。您只需使用

获取File
 File file = new File(Environment.getExternalStorageDirectory()
                    + "your_path/your_xml.xml");

然后进行进一步处理。

<强>更新

如果您需要different种类型XML Parsers的示例,可以download complete中的{{1}} {{1}}示例。

答案 1 :(得分:0)

像这样使用FileReader对象:

/**
  * Fetch the entire contents of a text file, and return it in a String.
  * This style of implementation does not throw Exceptions to the caller.
  *
  * @param aFile is a file which already exists and can be read.
  * File file = new File(Environment.getExternalStorageDirectory() + "file path");
  */
  static public String getContents(File aFile) {
    //...checks on aFile are elided
    StringBuilder contents = new StringBuilder();

    try {
      //use buffering, reading one line at a time
      //FileReader always assumes default encoding is OK!
      BufferedReader input =  new BufferedReader(new FileReader(aFile));
      try {
        String line = null; //not declared within while loop
        /*
        * readLine is a bit quirky :
        * it returns the content of a line MINUS the newline.
        * it returns null only for the END of the stream.
        * it returns an empty String if two newlines appear in a row.
        */
        while (( line = input.readLine()) != null){
          contents.append(line);
          contents.append(System.getProperty("line.separator"));
        }
      }
      finally {
        input.close();
      }
    }
    catch (IOException ex){
      ex.printStackTrace();
    }

    return contents.toString();
  }

此外,您还需要添加访问设备上SDCard的权限。

相关问题