Find all files on sd card

2019-02-23 20:36发布

I want to find all files stored on sdCard. I used this code:

List<File> dir = new ArrayList<File>();
List<File> files = new ArrayList<File>();

   File root = new File (Environment.getExternalStorageDirectory().getAbsolutePath());

    scan(root); // find root directories

    for (File f : dir) { // find in root...
       scan(f);
    }

    Log.i("files", "" + files.size());
    Log.i("dir", "" + dir.size());


}

 public void scan (File path) {

    for (File f : path.listFiles()) {
        if (f.isFile()) {
            files.add(f);
        }
        else {
            dir.add(f);
        }
    }
}

But I have problem with this exception: "java.util.ConcurrentModificationException" I change list (dir) and loop it. The ListIterator doesn't help.

1条回答
Root(大扎)
2楼-- · 2019-02-23 20:41

You can't add to a list while you're iterating over it. Try this instead:

List<File> dir = new ArrayList<File>();
List<File> files = new ArrayList<File>();

   File root = new File (Environment.getExternalStorageDirectory().getAbsolutePath());

    List<File> rootDirs = //... code to find root directories

    for (File f : rootDirs) { // find in root...
       scan(f);
    }

    Log.i("files", "" + files.size());
    Log.i("dir", "" + dir.size());


}

 public void scan (File path) {

    for (File f : path.listFiles()) {
        if (f.isFile()) {
            files.add(f);
        }
        else {
            dir.add(f);
            scan(f);
        }
    }
}
查看更多
登录 后发表回答