Search code examples
androidandroid-sdcard

List all text files present on SD card


I am using the following code to list down all the files present on the SD card. However I just want to list down all the text files can some body tell me how to add a file filter. Similarly I need to fetch the image files as well. Following is my code:

public ArrayList<String> GetFiles(String DirectoryPath) {
    ArrayList<String> MyFiles = new ArrayList<String>();
    File f = new File(DirectoryPath);

    f.mkdirs();
    File[] files = f.listFiles();
    if (files.length == 0)
        return null;
    else {
        for (int i=0; i<files.length; i++) 
            MyFiles.add(files[i].getName());
    }

    return MyFiles;
}

Solution

  • Use .endsWith() method from Java String Class to check File Extension from file path.

    Method:

    public boolean endsWith(String suffix)
    

    Your Code something like,

    private List<String> ReadSDCard()
    {
         //It have to be matched with the directory in SDCard
         File f = new File("your path");
    
         File[] files=f.listFiles();
    
         for(int i=0; i<files.length; i++)
         {
          File file = files[i];
          /*It's assumed that all file in the path are in supported type*/
          String filePath = file.getPath();
          if(filePath.endsWith(".txt")) // Condition to check .txt file extension
          tFileList.add(filePath);
         }
     return tFileList;
    }