Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list up all files with a certain extension on a device

I want to find all the files, in my case pdf's, on a device. Now I wrote this code:

File images = Environment.getExternalStorageDirectory();
        mImagelist = images.listFiles(new FilenameFilter(){
            public boolean accept(File dir, String name)
            {
                return ((name.endsWith(".pdf")));
            }
        });

This code finds only one pdf
/storage/emulated/0/HTC_One_WWE_User_Guide.pdf. I've got several other pdf's in my download folder.

How can I solve this?

like image 283
user1007522 Avatar asked Feb 14 '23 12:02

user1007522


2 Answers

Thanks to Juan.

private void findFiles(String[] paths) {
  for (String path: paths) {
    recursiveScan(new File(path));
  }
}

private void recursiveScan(File _file) {
  File[] files = _file.listFiles();
  if (files != null && files.length > 0) {
    for (File file: files) {
      if (file.isDirectory()) recursiveScan(file);
      if (file.isFile()) {
        Log.d("Scan: ", file.toString());
      }
    }
  }
}

You just need to give a File var from where to search.

like image 91
user1007522 Avatar answered Feb 16 '23 01:02

user1007522


Get a list of files from the external storage directory, and iterate said list. This should allow you to see if the extension matches pdf and then add to a list or whatever you want to do:

File[] file = Environment.getExternalStorageDirectory().listFiles(); 
for (File f : file){
   if (f.isFile() && f.getpath().endswith(".pdf")) {
      //Add to your list 
   }
}

This wont go inside directories as far as I know, so you'll need to wrap it inside a method and do something like if f.isDirectory() re-call the method again to walk through the folder.

public void recursiveScan(File f) {
    File[] file = f.listFiles(); 
    for (File f : file){
        if (f.isDirectory()) recursiveScan(f);
        if (f.isFile() && f.getpath().endswith(".pdf")) {
            //Add to your list 
        }
    }
}

Which would be called something like recursiveScan(Environment.getExternalStorageDirectory());

Disclaimer: I haven't tested it, so some stuff may be off, but it should give you a general idea of how to get to do it.

like image 35
Juan Cortés Avatar answered Feb 16 '23 01:02

Juan Cortés