Java读取某目录下所有文件名


Java读取某目录下所有文件名:

  1. import java.io.*;  
  2. import java.util.*;  
  3. import org.apache.log4j.Logger;  
  4.   
  5. /** 
  6.  * 读取目录及子目录下指定文件名的路径, 返回一个List 
  7.  */  
  8.   
  9. public class FileViewer {  
  10.  private static Logger logger = Logger.getLogger(FileViewer.class);  
  11.   
  12.  /** 
  13.   * @param path 
  14.   *            文件路径 
  15.   * @param suffix 
  16.   *            后缀名, 为空则表示所有文件 
  17.   * @param isdepth 
  18.   *            是否遍历子目录 
  19.   * @return list 
  20.   */  
  21.  public static List<String> getListFiles(String path, String suffix, boolean isdepth) {  
  22.   List<String> lstFileNames = new ArrayList<String>();  
  23.   File file = new File(path);  
  24.   return FileViewer.listFile(lstFileNames, file, suffix, isdepth);  
  25.  }  
  26.   
  27.  private static List<String> listFile(List<String> lstFileNames, File f, String suffix, boolean isdepth) {  
  28.   // 若是目录, 采用递归的方法遍历子目录     
  29.   if (f.isDirectory()) {  
  30.    File[] t = f.listFiles();  
  31.      
  32.    for (int i = 0; i < t.length; i++) {  
  33.     if (isdepth || t[i].isFile()) {  
  34.      listFile(lstFileNames, t[i], suffix, isdepth);  
  35.     }  
  36.    }     
  37.   } else {  
  38.    String filePath = f.getAbsolutePath();     
  39.    if (!suffix.equals("")) {  
  40.     int begIndex = filePath.lastIndexOf("."); // 最后一个.(即后缀名前面的.)的索引   
  41.     String tempsuffix = "";  
  42.   
  43.     if (begIndex != -1) {  
  44.      tempsuffix = filePath.substring(begIndex + 1, filePath.length());  
  45.      if (tempsuffix.equals(suffix)) {  
  46.       lstFileNames.add(filePath);  
  47.      }  
  48.     }  
  49.    } else {  
  50.     lstFileNames.add(filePath);  
  51.    }  
  52.   }  
  53.   return lstFileNames;  
  54.  }  
  55. }  

相关内容