Search the entire SD card for a specific file

I know how to search for a file, but using a specific path, example / sdcard / picture / file. Is there any way to search for this particular file. Example: file search. Then the application will find it in / sdcard / picture. Then uninstall it.

Any help? Thanks (I know how to erase a file, but I need to write all the way)

0
source share
2 answers

You can solve this problem recursively, starting from the root directory of the external memory / SD card.

Incorrect code from my head (method names may be incorrect)

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 this name on your SD card, you will have to use the List to collect and return all matches found.

+3
source

Try the following:

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

Source: https://habr.com/ru/post/1795938/


All Articles