简体   繁体   中英

How to get all the filenames in android directory?

Im trying to list all the files in a particular folder of my android emulator and i keep getting null answer.

Heres my code:

File sdCardRoot = Environment.getExternalStorageDirectory();
File[] file= new File(sdCardRoot+"path");
for (File f : file.listFiles()) {
    if (f.isFile())
        String name = f.getName();

}

This doesnt seem to work dont know why.

I've split the function in two parts, first function gets all the files in the given path and the second function gets the filenames from the file array.

public File[] GetFiles(String DirectoryPath) {
    File f = new File(DirectoryPath);
    f.mkdirs();
    File[] file = f.listFiles();
    return file;
}

public ArrayList<String> getFileNames(File[] file){
    ArrayList<String> arrayFiles = new ArrayList<String>();
     if (file.length == 0)
            return null;
        else {
            for (int i=0; i<file.length; i++) 
                arrayFiles.add(file[i].getName());
        }

    return arrayFiles;
}

change

File[] file= new File(sdCardRoot+"path");

with

File[] file= new File(sdCardRoot, "path");

and make sure the directory path exits

Just Check this:

  List<File> files = getListFiles(new File("YOUR ROOT")); 
  private 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 {
          if(file.getName().endsWith(".csv")) {
              inFiles.add(file);
          }
      }
}

return inFiles;

Since sdCardRoot is instance of File , sdCardRoot+"path" will return the same thing as sdCardRoot.toString() + "path" .

However, calling file.toString() returns file name, but not absolute path. You need to call sdCardRoot.getAbsolutePath() + "path" .

Also, make sure that you have allowed the emulator to use a certain amount of memory for external storage.

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