2

I looking for help to list all files in Android external storage device. I want to look up in all the folders, including the subfolders for the main folder. Is there a way to this?

I have worked on a basic one, but I still haven't got the desired result. It doesn't work.

Here is my code:

File[] files_array;
files_array = new File(Environment.getExternalStorageDirectory().getAbsolutePath()).listFiles();

This method returns 0 size. What is the matter? This is my activity:

public class Main extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        List<File> files = getListFiles(Environment.getExternalStorageDirectory());
        setListAdapter(new ArrayAdapter<File>(Main.this, android.R.layout.simple_list_item_1, files));
        Toast.makeText(this, "" + files.size(), Toast.LENGTH_LONG).show();
    }

    private List<File> getListFiles(File parentDir) {
        // On first call, parentDir is your sdcard root path
        ArrayList<File> inFiles = new ArrayList<File>(); // Initialize an array list to store file names
        File[] files = parentDir.listFiles(); // List all files in this directory
        for (File file : files) {

            if (file.isDirectory()) { // If the file is a directory
                inFiles.addAll(getListFiles(file)); // *** Call this recursively to get all lower level files ***
            }
        }
        return inFiles;
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mansour Fahad
  • 721
  • 2
  • 9
  • 23

7 Answers7

3

Here is a solution found on the web:

public void walkdir(File dir) {

    File[] listFile;
    listFile = dir.listFiles();

    if (listFile != null) {
        for (int i = 0; i < listFile.length; i++) {
            if (listFile[i].isDirectory()) {
                walkdir(listFile[i]);
            } else {
                if (listFile[i].getName().toLowerCase().endsWith(".pdf")) {
                    files_list.add(listFile[i]);
                }
            }
        }
    }
}

You actually only need calling the method above with the parent directory that you want to start with. I recommend to put Environment.getExternalStorageDirectory() in the parent directory so it will not change with different devices.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mansour Fahad
  • 721
  • 2
  • 9
  • 23
3
public void Search_Dir(File dir) {
    String pdfPattern = ".pdf";

    Log.d("check",
            "Environment.getExternalStorageDirectory()------"
                    + dir.getName());

    File FileList[] = dir.listFiles();
    Log.d("check",
            "filelist length---- "
                    + FileList.length);

    if (FileList != null) {
        for (int i = 0; i < FileList.length; i++) {

            if (FileList[i].isDirectory()) {
                Search_Dir(FileList[i]);
            } else {

                Log.d("check",
                        "for check from .pdf---- "
                                + FileList[i].getName());
                if (FileList[i].getName().endsWith(pdfPattern)) {
                    // here you have that file.
                    pdfArrayList.add(FileList[i].getPath());

                }
            }
        }
    }

}
Monu Gupta
  • 153
  • 1
  • 8
2

Conceptually, what you are doing is not complete. Your code only gives you a File for the root level directory. To determine all the files within this directory and the sub directories, you need recursive calls so that all the files are listed to the end of the folder levels.

private List<File> getListFiles(File parentDir) {
    // On first call, parentDir is your sdcard root path
    ArrayList<File> inFiles = new ArrayList<File>(); // initialize an array list to store file names
    File[] files = parentDir.listFiles(); // list all files in this directory
    for (File file : files) {
        if (file.isDirectory()) { // if the file is a directory
            inFiles.addAll(getListFiles(file)); // **CALL THIS RECURSIVELY TO GET ALL LOWER LEVEL FILES**
        } 

    }
    return inFiles;
}

Now call this function as:

getListFiles(Environment.getExternalStorageDirectory());

Now, you can add your ArrayList as a source to a List Control.

Bonus: If you would like to represent list the files in a tree like view, I would recommend you to look at https://code.google.com/p/tree-view-list-android/

Source: List all the files from all the folder in a single list

Search all .pdf file present in the Android device

Community
  • 1
  • 1
krammer
  • 2,598
  • 2
  • 25
  • 46
  • 1
    I followed your code but when I use the method above it returns a 0 size. I will edit my code so you have a clear idea about what I‘m talking about. – Mansour Fahad Sep 24 '13 at 05:15
  • 1
    @MansourFahad Did you add permission to access the external storage ? – krammer Sep 24 '13 at 05:59
  • Yes mate it was there but I don't know why it was fail. Anyway I have solved the problem with the code that I provide as answer. Thank you very much. – Mansour Fahad Sep 25 '13 at 07:32
0

Try with this: The java.io package has been reimplemented within Android. You are able to use the same mechanisms in Android as you do in Java.

File fileList = new File("/sdcard"); // Path which you want to read
if (fileList != null) {
    File[] files = fileList.listFiles();
        for (File f : files) {
            // Do something with the files
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pradip
  • 3,189
  • 3
  • 22
  • 27
0

I used this code:

    private File[] listOfDir;

    /* ... */

    TextView tv = (TextView) rootView.findViewById(R.id.textView1);
    listOfDir = show();
    String temp = "";
    if (listOfDir != null) {
        for (File i : listOfDir) {
            temp += i.getName() + '\n';
        }
    } else {
        temp = "null";
    }
    tv.setText(temp);
    ...

    public File[] show() {
        File[] dirs = null;
        File dir = new File( /* Your path */ );
        dirs = dir.listFiles();
        return dirs;
    }

And just call show to get list all the name.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
willsantoso
  • 137
  • 1
  • 1
  • 9
0

I think this will help. First you need to fetch the contents of the SD card as shown below:

public class FileList extends ListActivity
{
    private File file;
    private List<String> myList;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        myList = new ArrayList<String>();

        String root_sd = Environment.getExternalStorageDirectory().toString();
        file = new File(root_sd + "/external_sd");
        File list[] = file.listFiles();

        for(int i=0; i< list.length; i++)
        {
            myList.add(list[i].getName());
        }

        setListAdapter(new ArrayAdapter<String>(
                           this,
                           android.R.layout.simple_list_item_1,
                           myList));
    }

Now that you have all the files and folders from your sdcard in your listview, whenever, you go into a folder, then you need to fetch the contents of that folder as shown below:

protected void onListItemClick(ListView l, View v, int position, long id)
{
    super.onListItemClick(l, v, position, id);

    File temp_file = new File(file, myList.get(position));

    if(!temp_file.isFile())
    {
        file = new File(file, myList.get(position));
        File list[] = file.listFiles();

        myList.clear();

        for(int i=0; i< list.length; i++)
        {
            myList.add(list[i].getName());
        }
        Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show();
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, myList));
    }
}

And again on pressing back you need to load back the contents of your previous folder as shown below:

@Override
public void onBackPressed() {
    String parent = file.getParent().toString();
    file = new File(parent);
    File list[] = file.listFiles();

    myList.clear();

    for(int i=0; i< list.length; i++)
    {
        myList.add(list[i].getName());
    }
    Toast.makeText(getApplicationContext(), parent, Toast.LENGTH_LONG).show();
    setListAdapter(new ArrayAdapter<String>(
                     this,
                     android.R.layout.simple_list_item_1,
                     myList));

I think this is what you need.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zax
  • 2,870
  • 7
  • 52
  • 76
0

I wrote a tutorial on this a while ago and still use this from time to time. Have a look; you might find what you need.

playing-with-sdcard-in-android

Try this:

If you don't want the directory to be listed, put files.add(file1[i]); line in the else block:

public class MainActivity extends ListActivity {

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        File file[] = Environment.getExternalStorageDirectory().listFiles();
        recursiveFileFind(file);

        setListAdapter(new ArrayAdapter<File>(MainActivity.this,
                android.R.layout.simple_list_item_1, files));
        Toast.makeText(this, "" + files.size(), Toast.LENGTH_LONG).show();
    }

    public void recursiveFileFind(File[] file1) {
        int i = 0;
        String filePath = "";
        if (file1 != null) {
            while (i != file1.length) {
                filePath = file1[i].getAbsolutePath();
                files.add(file1[i]);
                if (file1[i].isDirectory()) {
                    File file[] = file1[i].listFiles();
                    recursiveFileFind(file);
                }
                else{
                }

                i++;
                Log.d(i + "", filePath);
            }
        }
    }

}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
saiful103a
  • 1,109
  • 7
  • 13