[英]Filtering files in a directory on Android
In my app i am getting the images from a folder in gallery and saving it into an array list.Now i want to extract only the files with .jpg extension.How can i do it在我的应用程序中,我从图库中的文件夹中获取图像并将其保存到数组列表中。现在我只想提取扩展名为 .jpg 的文件。我该怎么做
The code for saving to array list is保存到数组列表的代码是
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;
}
You can use FilenameFilter interface to Filter the Files.您可以使用FilenameFilter接口来过滤文件。
Change your codeline更改代码行
File[] files=f.listFiles();
as below:如下:
File[] jpgfiles = f.listFiles(new FileFilter() {
@Override
public boolean accept(File file)
{
return (file.getPath().endsWith(".jpg")||file.getPath().endsWith(".jpeg"));
}
});
Use .endsWith()
method from Java String Class to check File Extension from file path.使用Java String Class 中的
.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("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;
}
private List<String> ReadSDCard()
{
String extension = "";
File f = new File("sdcard/data/crak");
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
int ind = files[i].getPath().lastIndexOf('.');
if (ind > 0) {
extension = files[i].getPath().substring(i+1);// this is the extension
if(extension.equals("jpg"))
{
tFileList.add(file.getPath());
}
}
}
return tFileList;
}
In your code add the following:在您的代码中添加以下内容:
String filePath = file.getPath();
if(filePath.endsWith(".jpg"))
tFileList.add(filePath);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.