2

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

4 回答 4

28

您可以使用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"));
            }
});
于 2013-01-16T07:24:02.597 回答
2

使用Java String 类.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;
}
于 2013-01-16T07:16:55.730 回答
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;
}
于 2013-01-16T07:17:27.320 回答
-2

在您的代码中添加以下内容:

          String filePath = file.getPath();
          if(filePath.endsWith(".jpg")) 
          tFileList.add(filePath);
于 2013-01-16T07:28:15.883 回答