从SD卡读取一个.xml文件

4
我有一个名为bkup.xml的xml文件存储在sdcard"/ sdcard / bkup.xml"中。
创建bkup.xml时,我使用了xmlSerialization。
我想从bkup.xml文件中检索数据。
我看过许多示例,但几乎所有示例都是使用资源文件并使用URL作为资源。 但没有一个示例给出sdcard文件的路径。
我不知道如何从该文件中提取数据并解析它。
提前感谢。
任何建议都将不胜感激。

请发布您的代码以及您已经尝试过的内容。 - ingsaurabh
你能告诉我任何接受文件路径位置来进行解析的方法吗? - Vaibhav Vajani
2个回答

5

这里有一个带源代码的完整示例。您只需要使用File获取它。

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

然后进行进一步的处理。

更新

如果您需要不同类型的XML解析器示例,可以从此处下载完整的示例。


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

同时,您需要添加访问设备SD卡的权限。


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