package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class KeyWordMatch {
public static void main(String[] args) {
String path = "C:\\Users\\JiangLi\\Desktop\\DBConnection.java"; //文件路径
List<String> keyWords = new ArrayList<String>(); //关键字map
keyWords.add("String");
keyWords.add("public");
keyWords.add("void");
keyWords.add("new");
keyWords.add("try");
keyWords.add("static");
keyWords.add("import");
try {
match(path,keyWords);
match2(path,keyWords);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 运用split方法确定关键字个数
* @param path
* @param keyWords
* @throws Exception
*/
private static void match2(String path, List<String> keyWords) throws Exception {
File file = new File(path);
if(file.exists()){
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,"utf-8");
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String data = null;
while((data=br.readLine())!=null){
sb.append(data+"\n");
}
//System.out.println("Java文件内容如下:");
//System.out.println(sb.toString());
System.out.println("各关键字出现次数如下:");
for(String keyword:keyWords){
String content = sb.toString();
String[] strs = content.split(keyword);
System.out.println("出现关键字"+keyword+"的个数为:"+(strs.length-1));
}
}else{
System.out.println("文件不存在!");
}
}
private static void match(String path, List<String> keyWords) throws Exception {
File file = new File(path);
if(file.exists()){
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,"utf-8");
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String data = null;
while((data=br.readLine())!=null){
sb.append(data+"\n");
}
//System.out.println("Java文件内容如下:");
//System.out.println(sb.toString());
System.out.println("各关键字出现次数如下:");
for(String keyword:keyWords){
int count=0;
boolean boo = true;
String content = sb.toString();
while(boo){
int index = content.indexOf(keyword);
if(index == -1){
boo = false;
}else{
count++;
content = content.substring(index+keyword.length());
}
}
System.out.println("出现关键字"+keyword+"的个数为:"+count);
}
}else{
System.out.println("文件不存在!");
}
}
}
转载于:https://my.oschina.net/jiangli0502/blog/142157