我从图像库文件夹中获取图像,并把它保存在一个数组列表中。现在我只想提取有.jpg扩展的文件。如何实现呢?
private List<String> ReadSDCard()
{
//It have to be matched with the directory in SDCard
File f = new File("sdcard/data/crak");
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*/
tFileList.add(file.getPath());
}
return tFileList;
}
使用 Java String 类中的.endsWith()
方法来检查文件路径中的 File Extension。
Method:
public boolean endsWith(String suffix)
代码如下:
private List<String> ReadSDCard()
{
//It have to be matched with the directory in SDCard
File f = new File("sdcard/data/crak");
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(".jpg")) // Condition to check .jpg file extension
tFileList.add(filePath);
}
return tFileList;
}
if (file.getAbsolutePath().endsWith(".jpg")) {
tFileList.add(file.getPath());
}
你可以使用 FilenameFilter 接口来过滤文件。
把代码:File[] files=f.listFiles();
改成:
File[] jpgfiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name)
{
return (name.endsWith(".jpg")||name.endsWith(".jpeg"));
}
});