Rotary Heart
Rotary Heart

Reputation: 1969

Search entire sdcard for a specific file

I know how to search a file, but using a specific path, example /sdcard/picture/file. Is there a way to search for that specific file. Example: search for file. Then the app locate it in /sdcard/picture. Then erase it.

Any help? Thanks (I know how to erase a file, but have to write the entire path)

Upvotes: 0

Views: 3107

Answers (2)

tiguchi
tiguchi

Reputation: 5410

You can solve that problem recursively starting from the root directory of the external storage / SD card.

Some untested code out of my head (method names could be wrong)

public File findFile(File dir, String name) {
    File[] children = dir.listFiles();

    for(File child : children) {
        if(child.isDirectory()) {
           File found = findFile(child, name);
           if(found != null) return found;
        } else {
            if(name.equals(child.getName())) return child;
        }
    }

    return null;
}

If you want to find all occurrences of that file name on your SD card you'll have to use a List for collecting and returning all found matches.

Upvotes: 3

danielpiestrak
danielpiestrak

Reputation: 5439

Try this:

public class Test {
    public static void main(String[] args) {
        File root = new File("/sdcard/");
        String fileName = "a.txt";
        try {
            boolean recursive = true;

            Collection files = FileUtils.listFiles(root, null, recursive);

            for (Iterator iterator = files.iterator(); iterator.hasNext();) {
                File file = (File) iterator.next();
                if (file.getName().equals(fileName))
                    System.out.println(file.getAbsolutePath());
                    file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 0

Related Questions