drarkayl
drarkayl

Reputation: 1017

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.

Upvotes: 1

Views: 5835

Answers (4)

user2544287
user2544287

Reputation: 124

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;
}

Upvotes: 10

asenovm
asenovm

Reputation: 6517

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.

Upvotes: 0

Shani Goriwal
Shani Goriwal

Reputation: 2104

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;

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157437

change

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

with

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

and make sure the directory path exits

Upvotes: 2

Related Questions