Search code examples
androidfilexml-parsingsd-card

How to search a xml file from android mobile sd card


I am having a XML file in sd card. I want to search the entire sd card and find that file. After that i have to parse that file.

I have done a like below.But could not get the file..

static final String PATH = Environment.getExternalStorageDirectory()
        .getPath() + "/download/";
static final String FILE_NAME = "aura_key.xml";

static File isKeyExist() {
     File file = new File(PATH+FILE_NAME);

     if(file.exists())
     {
         return file;
     }else

    return file;

}

Thanks in advance.


Solution

  • If you want to search in the whole external storage, you need to look in all directories and subdirectories etc...

    here's a sample solution, just call the first method with your filename (including file extension in your case :

    searchForFileInExternalStorage("aura_key.xml");
    

    and here are the methods :

    public File searchForFileInExternalStorage(String filename) {
        File storage = Environment.getExternalStorageDirectory();
    
        return searchForFileInFolder(filename, storage);
    }
    
    public File searchForFileInFolder(String filename, File folder) {
        File[] children = folder.listFiles();
        File result;
    
        for (File child : children) {
            if (child.isDirectory()) {
                result = searchForFileInFolder(filename, child);
                if (result != null) {
                    return result;
                }
            } else {
                // replace equals by equalsIgnoreCase if you want to ignore the
                // case of the file name
                if (child.getName().equals(filename)) {
                    return child;
                }
            }
        }
    
        return null;
    }