问题
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