0

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)

Rotary Heart
  • 1,899
  • 3
  • 29
  • 44

2 Answers2

3

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.

tiguchi
  • 5,392
  • 1
  • 33
  • 39
0

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();
        }
    }
}
danielpiestrak
  • 5,279
  • 3
  • 30
  • 29
  • I'm getting unknown entity from FileUtils – Rotary Heart Jul 08 '12 at 21:59
  • This is because above example is not directly targeted at Android development. [FileUtils](http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html) is a component from the Apache Commons library. Furthermore be careful and do not hard-code paths to the external storage. There is no guarantee, that all devices have their external storage mounted in a directory called "/sdcard/". You need to use [SDK methods](http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29) for getting the proper path. – tiguchi Jul 08 '12 at 22:09
  • And what about search entire files? Even phone ones? – Rotary Heart Jul 08 '12 at 22:18