简体   繁体   English

列出SD卡上存在的所有文本文件

[英]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. 我正在使用以下代码列出SD卡上存在的所有文件。 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. 使用Java字符串类中的 .endsWith()方法从文件路径中检查文件扩展名。

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

You can use FilenameFilter Interface to Shortlist all TextFiles are any related files to an Array. 您可以使用FilenameFilter接口将所有TextFiles短名单化为与Array相关的任何文件。 You can check my answer here to shortlist only image files from SD card. 您可以在此处查看我的答案 ,仅将来自SD卡的图像文件列出。

import org.apache.commons.io.FilenameUtils

String extension=FilenameUtils.getExtension(filepath);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM