List all text files present on SD card

 ̄綄美尐妖づ 提交于 2019-12-12 00:35:04

问题


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

回答1:


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



回答2:


You can use FilenameFilter Interface to Shortlist all TextFiles are any related files to an Array. You can check my answer here to shortlist only image files from SD card.




回答3:


import org.apache.commons.io.FilenameUtils

String extension=FilenameUtils.getExtension(filepath);


来源:https://stackoverflow.com/questions/14374068/list-all-text-files-present-on-sd-card

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!