且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

列出SD卡上的所有文本文件present

更新时间:2023-09-28 09:36:40

使用 .endsWith()从方法的的Java String类以检查文件从扩展文件路径。

方法:

 公共布尔的endsWith(字符串后缀)

您code类似,

 私人列表<串GT; ReadSDCard()
{
     //它必须与SD卡中的目录相匹配
     文件f =新的文件(路径);     文件[] =文件f.listFiles();     的for(int i = 0; I< files.length;我++)
     {
      文件fil​​e =文件[I]
      / *它假定路径中的所有文件都支持的类型* /
      串文件路径= file.getPath();
      如果(filePath.endsWith(TXT))//条件检查.txt文件扩展名
      tFileList.add(文件路径);
     }
 返回tFileList;
}

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

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