简体   繁体   中英

Android: How to list all the files in a directory in to an array?

I have a variable "directorypath". It has the path to a directory in sd card.

Ex: "sdcard/images/scenes"

Now, I want to list all the files in the "directorypath" and want an Array to store all the file names in it.

Ex: Array[0]= Filename1, Array[1]= Filename2 Etc... 

I tried something like Array[] myArray = directorypath.listfile(); but didn't work..! Can anyone give me the code or at least help me? Much appreciated.

I think the problem you are facing is related to the external storage directory file path. Don't use whole path as variable if you can access with environment.

String path = Environment.getExternalStorageDirectory().toString()+"/images/scenes"; 

Also, you can use the API listfiles() with file object and it will work. For eg ::

File f = new File(path);        
File file[] = f.listFiles();

Try the following code which may help you

List<File> getListFiles(File parentDir) {
    ArrayList<File> inFiles = new ArrayList<File>();
    File[] files = parentDir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            inFiles.addAll(getListFiles(file));
        } else {
                inFiles.add(file);
        }
    }
    return inFiles;
}

This will return you list of files under the directory you specified.
From the File object in list.. you will get all information about files you required.

According to your error message "Cannot resolve listFiles()", you are trying to call a method on a String object, when you actually want to be calling that on a File object.

Create a new File object,

String parentDirectory = "path/to/files";
File dirFileObj = new File(parentDirectory);
File[] files = dirFileObj.listFiles();

I was indeed calling a function for improper data type. ie, listfiles() won't work on String type variable..!!

SO, I created a File type variable and a File[] array to pass the list of files..! This solved the issue.

its very simple Just two lines of code

 File mListofFiles = new File(Environment.getExternalStorageDirectory.getAbsolutePath()+"/",childpath:Foldername);
 File f = new File(mListofFiles.toString());        
 File file[] = f.listFiles();     

Try the following code:

File externalStorageDirectory = Environment.getExternalStorageDirectory();
File folder = new File(externalStorageDirectory.getAbsolutePath() + "/FilePath");
File file[] = folder.listFiles();
if (file.length != 0) {
    for (int i = 0; i < file.length; i++) {
        //here populate your list
    }
} else {
    //no file available
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM