zoukankan      html  css  js  c++  java
  • [Java] [查找文件] [递归]]

    // 工具方法
    private static FilenameFilter getFilter(final String mode) {
    		return new FilenameFilter() {
    			Pattern pattern;
    			
    			{
    				pattern = Pattern.compile(mode);
    			}
    			
    			public boolean accept(File file, String name) {
    				return pattern.matcher(name).matches();
    			}
    			
    		};
    }
    
    // 调用该接口, 可修改为返回 fs : File[]
    public static void find(File dir) {
    		if (dir.isDirectory()) {
    			File[] tfs = dir.listFiles();
    			// 复制子目录
    			File[] cfs = new File[tfs.length];
    			int count = 0;
    			for (File fs : tfs) {
    				if (fs.isDirectory()) {
    					cfs[count++] = fs;
    				}
    			}
    			// 递归遍历子目录
    			for (int i = 0; i < count; i++) {
    				find(cfs[i]);
    			}
    			// 将该目录下的所有文件夹匹配正则表达式
    			File[] fs = dir.listFiles(getFilter(".+\.java"));
    			/*
    			// 由于需要递归, 所以不能在此创建匿名内部类, 而应使用单例
    			fs = dir.listFiles(
    				new FilenameFilter() {
    					Pattern pattern;
    					
    					// 匿名内部类的构造块
    					{
    						pattern = Pattern.compile(".+\.java");
    					}
    					
    					// 对于一个 File 数组, 将所有元素依次传入该回调函数, 以询问是否同意该元素加入集合, 其中 namne 等价于 f.getName()
    					public boolean accept(File f, String name) {
    						return pattern.matcher(name).matches();
    					}
    			});
    			*/
    			// 打印当前已筛选的文件的全路径
    			for(File f : fs) {
    				try{
    					System.out.println(f.getCanonicalPath());
    				} catch(IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    }
    

      

  • 相关阅读:
    redhat 6.7 telnet rpm 安装包
    linux下网络配置 命令
    修复南尼U盘
    mac获取root权限
    ubuntu二进制包安装openresty
    ubuntu18源码包安装openresty
    Python监控rabbitmq的代码
    win10不能将文件拖到另外一个程序中去的解决办法
    docker配置远程管理端口
    nginx的代理配置
  • 原文地址:https://www.cnblogs.com/develon/p/8607809.html
Copyright © 2011-2022 走看看