递归调用的方式遍历SD卡上的所有图片

来源:互联网 发布:如何培养编程思维 编辑:程序博客网 时间:2024/05/26 07:29
  1. private ArrayList<String> imgPath=new ArrayList<String>();   //定义一个数组用于保存文件路径  
  2.   
  3. private static String[] imageFormat=new String[]{"jpg","bmp","gif"};      //定义图片格式  
  4.   
  5. private boolean isImageFile(String path){                                       //判断是否为图片文件的方法  
  6.     for (String format:imageFormat){  
  7.         if (path.contains(format)){                                 //如果文件名字包含定义的格式后缀,则返回true  
  8.             return true;  
  9.         }  
  10.           
  11.     }  
  12.     return false;  
  13. }  
  14.   
  15. private void getSdCardImgFile(String url){                   //获取指定路径下的指定格式图片文件,传入路径参数  
  16.     File files=new File(url);       //新定义一个文件,路径则为传入的url  
  17.     File[] file=files.listFiles();          //遍历该文件所有的子文件夹生成文件夹数组  
  18.     for (File f:file){              //for循环遍历到文件数组  
  19.         if(f.isDirectory()){            //如果为文件夹,则递归调用此方法遍历子文件夹  
  20.             getSdCardImgFile(f.getAbsolutePath());  //递归调用  
  21.         }else {  
  22.             if (isImageFile(f.getPath())){  //如果文件是图片文件  
  23.                   
  24.                 imgPath.add(f.getAbsolutePath());//获取绝对路径,返回到定义好的数组中。  
  25.             }  
  26.         }  
  27.     }  
  28. }  
0 0