过滤Android上目录中的文件

时间:2013-01-16 07:15:13

标签: android

在我的应用程序中,我从图库中的文件夹中获取图像并将其保存到数组列表中。现在我只想提取带有.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;
    }

4 个答案:

答案 0 :(得分:21)

您可以使用FilenameFilter界面过滤文件。

更改您的代码行

File[] files=f.listFiles();

如下:

File[] jpgfiles = f.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file)
            {
                return (file.getPath().endsWith(".jpg")||file.getPath().endsWith(".jpeg"));
            }
});

答案 1 :(得分:2)

使用 Java String Class 中的.endsWith()方法检查文件路径中的文件扩展名。

方式:

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

答案 2 :(得分:0)

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

答案 3 :(得分:-1)

在您的代码中添加以下代码

          String filePath = file.getPath();
          if(filePath.endsWith(".jpg")) 
          tFileList.add(filePath);