Reading an .xml file from sdcard

2019-01-24 18:24发布

问题:

I have one xml file called bkup.xml stored inside sdcard "/sdcard/bkup.xml".

For creating bkup.xml I have used xmlSerialization.

I want to retrieve data from that bkup.xml file.

I have seen many examples but almost most of them are using resource file and using URL as a resource. But no one have example of giving a path of sdcard file.

I don't know how to fetch data from that file and parse it.

Thanks in advance.

Any suggestion will be appreciated

回答1:

Here is an complete example with source. You just to get the File using

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

Then do the further processing.

UPDATE

If you need example for different types of XML Parsers you can download complete example from here.



回答2:

Use the FileReader Object like this :

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

Also you need to add permission to access the SDCard on the device.