---
title: "在指定路径下搜索含指定关键词的所有文件"
author: "bcworld"
date: "2012-10-28T08:58:07Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-10-28T09:00:26Z"
id: 1706753
url: "https://bcworld.iteye.com/blog/1706753"
---

这个功能类似notepad++的文件搜索功能，如全词匹配“int”的搜索结果如下所示：

 

![](http://dl.iteye.com/upload/attachment/0075/7376/1ae72f6f-97d2-320b-9a70-8cbc358f5b21.png)

 

但是搜索结果呈现出来的形式可能不是我们需要的，如我们只需要知道哪些文件有关键词，把结果导出到EXCEL中等等，这时就需要我们自己编码了，下面只是个参考：

 

```
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckKeyWord {
	public final String fileType="java";//文件扩展名
	public static final String checkDir="E:\\svn\\mysvnproject\\check1\\ebay";
	public final boolean skipDirWithPointStart=true;//跳过以.号开头的文件夹
	public static String keywords[]={"int","Integer"};//搜索的关键词
	public static Map<String, Integer> report=new HashMap<String,Integer>();
	public static void main(String[] args) {
		CheckKeyWord c=new CheckKeyWord();
		try {
			c.check(checkDir);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Set<String> files=report.keySet();
		Iterator<String> iterator=files.iterator();
		while(iterator.hasNext()){
			String file=iterator.next();
			Integer count=report.get(file);
			System.out.println(file+":\t("+count+" hits)");
		}
		
		
	}
	private void check(String dir) throws Exception{
		if (keywords.length==0) {
			System.out.println("请列出关键词");
			return;
		}
		File dirs=new File(dir);
		File files[]=dirs.listFiles();
		FileReader fReader=null;
		BufferedReader br=null;
		StringBuffer reg=new StringBuffer();
		for (int i = 0; i < keywords.length; i++) {
			reg.append(".* "+keywords[i]+" .*|");
		}
		String regex=reg.substring(0,reg.length()-1);
		Pattern pattern=Pattern.compile(regex);
		Matcher matcher=null;
		for(File tempFile:files){
			//跳过以点开头的文件夹，如.svn文件夹
			if (skipDirWithPointStart) {
				if (tempFile.isDirectory()) {
					check(tempFile.getAbsolutePath());
				} else {
					//读到某个文件
					if (checkFileType(tempFile,fileType)) {
						fReader=new FileReader(tempFile);
						br=new BufferedReader(fReader);
						String s=null;
						while((s=br.readLine())!=null){
							matcher=pattern.matcher(s);
							if (matcher.matches()) {
								//读取到的一行含给定关键字
								String absPath = tempFile.getAbsolutePath();
								if (!report.containsKey(absPath)) {
									report.put(absPath, 1);
								} else {
									report.put(absPath, report.get(absPath)+1);
								}
								System.out.println(absPath+"\t"+s);//文件全路径+含关键词的文本
							}
							
						}
					}
				}
			}
		}
	}
	private boolean checkFileType(File file, String fileType) {
		String fileName=file.getName();
		if (fileName.endsWith(fileType)) {
			return true;
		}
		return false;
	}
}
```

 

程序执行结果如下：

![](http://dl.iteye.com/upload/attachment/0075/7378/9d7a9857-2d49-32dd-8f7d-8d767fb04b9c.png)