文件内容、关键字匹配,split 和 indexOf 均可实现

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值