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

import java.io.*;
import java.util.*;
import org.apache.log4j.Logger;

/**
 * 读取目录及子目录下指定文件名的路径, 返回一个List
 */

public class FileViewer {
 private static Logger logger = Logger.getLogger(FileViewer.class);

 /**
  * @param path
  *            文件路径
  * @param suffix
  *            后缀名, 为空则表示所有文件
  * @param isdepth
  *            是否遍历子目录
  * @return list
  */
 public static List<String> getListFiles(String path, String suffix, boolean isdepth) {
  List<String> lstFileNames = new ArrayList<String>();
  File file = new File(path);
  return FileViewer.listFile(lstFileNames, file, suffix, isdepth);
 }

 private static List<String> listFile(List<String> lstFileNames, File f, String suffix, boolean isdepth) {
  // 若是目录, 采用递归的方法遍历子目录  
  if (f.isDirectory()) {
   File[] t = f.listFiles();
   
   for (int i = 0; i < t.length; i++) {
    if (isdepth || t[i].isFile()) {
     listFile(lstFileNames, t[i], suffix, isdepth);
    }
   }   
  } else {
   String filePath = f.getAbsolutePath();   
   if (!suffix.equals("")) {
    int begIndex = filePath.lastIndexOf("."); // 最后一个.(即后缀名前面的.)的索引
    String tempsuffix = "";

    if (begIndex != -1) {
     tempsuffix = filePath.substring(begIndex + 1, filePath.length());
     if (tempsuffix.equals(suffix)) {
      lstFileNames.add(filePath);
     }
    }
   } else {
    lstFileNames.add(filePath);
   }
  }
  return lstFileNames;
 }
}

 
  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值