简体   繁体   中英

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM