【问题标题】:Reading an .xml file from sdcard从 sdcard 读取 .xml 文件
【发布时间】:2012-03-04 20:25:23
【问题描述】:

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

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

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

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

我不知道如何从该文件中获取数据并对其进行解析。

提前致谢。

任何建议将不胜感激

【问题讨论】:

  • 发布你的代码你尝试了什么
  • 你能告诉我任何接受文件位置路径进行解析的方法吗?

标签: android xml xml-parsing


【解决方案1】:

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

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

然后做进一步的处理。

更新

如果您需要 different 类型的 XML Parsers 的示例,您可以使用 download complete 来自 here 的示例。

【讨论】:

    【解决方案2】:

    像这样使用 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 的权限。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多