基于Java的一个扫描路径下全部文件的程序

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

public class Directory {
    //处理多层文件筛选最好的数据结构是树,所以这里内部实现了一个简单的树
	static class FileTree{
		private String Parent;
		private List Childs = new ArrayList<>();
		
		public void setParent(String parent) {
			Parent = parent;
		}
		
		public List getChilds() {
			return Childs;
		}

		public String getParent() {
			return Parent;
		}

		public void add(FileTree fileTree) {
			this.Childs.add(fileTree);
		}
		
        //这里打印的方法做的不是很好,将就使用吧
		public static void PrintFileTree(FileTree fileTree,int time) {
			for(int i=0;i iterator = fileTree.getChilds().iterator();
				while(iterator.hasNext()) {
					PrintFileTree(iterator.next(),time);
				}
			}
		}
	}
	
    //实现文件名过滤器,用以使用正则表达式
	static class DirNameFilter implements FilenameFilter{
		private Pattern pattern;
		
		public DirNameFilter(String str) {
			pattern = Pattern.compile(str);
		}

		@Override
		public boolean accept(File dir, String name) {
			return pattern.matcher(name).matches();
		}
		
	}
	
    //第一个参数代表查询的文件路径,第二个参数代表正则表达式
	private static FileTree FileFound(String path,String regex) {
		FileTree fileTree = new FileTree();
		File file = new File(path);
		fileTree.setParent(file.getName());
		if(file.isDirectory()) {
			for(File f:file.listFiles(new DirNameFilter(regex))) {
				if(f.isDirectory()) {
					fileTree.getChilds().add(FileFound(f.getAbsolutePath(),regex));
				}else {
					FileTree fTree = new FileTree();
					fTree.setParent(f.getName());
					fileTree.getChilds().add(fTree);
				}
			}
		}
		return fileTree;
	}
	
	public static void main(String[] args) {
		FileTree.PrintFileTree(FileFound("E:\\maven\\apache-maven-3.5.4","!.*"),0);
	}
}

 

你可能感兴趣的:(java)