JAVA 搜索文本文件中的关键字

用JAVA实现对文本文件中的关键字进行搜索, 依据每一行,得到每一行中出现关键词的个数。使用java.io.LineNumberReader.java 进行行读取。示例如下:

一 实现类

package cn.youzi.test;

import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

/**
 * 对文本文件的关键词进行搜索
 * @author Abel
 *
 */
public class TextFileSearch {

	public void SearchKeyword(File file,String keyword) {
		//参数校验
		verifyParam(file, keyword);
		
		//行读取
		LineNumberReader lineReader = null;
		try {
			lineReader = new LineNumberReader(new FileReader(file));
			String readLine = null;
			while((readLine =lineReader.readLine()) != null){
				//判断每一行中,出现关键词的次数
				int index = 0;
				int next = 0;
				int times = 0;//出现的次数
				//判断次数
				while((index = readLine.indexOf(keyword,next)) != -1) {
					next = index + keyword.length();
					times++;
				}
				if(times > 0) {
					System.out.println("第"+ lineReader.getLineNumber() +"行" + "出现 "+keyword+" 次数: "+times);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//关闭流
			close(lineReader);
		}
	}

	/**
	 * 参数校验
	 * 
	 * <br>
	 * Date: 2014年11月5日
	 */
	private void verifyParam(File file, String keyword) {
		//对参数进行校验证
		if(file == null ){
			throw new NullPointerException("the file is null");
		}
		if(keyword == null || keyword.trim().equals("")){
			throw new NullPointerException("the keyword is null or \"\" ");
		}
		
		if(!file.exists()) {
			throw new RuntimeException("the file is not exists");
		}
		//非目录
		if(file.isDirectory()){
			throw new RuntimeException("the file is a directory,not a file");
		}
		
		//可读取
		if(!file.canRead()) {
			throw new RuntimeException("the file can't read");
		}
	}
	
	/**
	 * 关闭流
	 * <br>
	 * Date: 2014年11月5日
	 */
	private void close(Closeable able){
		if(able != null){
			try {
				able.close();
			} catch (IOException e) {
				e.printStackTrace();
				able = null;
			}
		}
	}

}

二 调用

package cn.youzi.test;

import java.io.File;

public class TextFileSearchTest {

	public static void main(String[] args) {

		TextFileSearch search = new TextFileSearch();
		search.SearchKeyword(new File("E:\\testDir\\news.txt"), "中国");
	}

}

结果 为:

第3行出现 中国 次数: 3
第5行出现 中国 次数: 4
第7行出现 中国 次数: 1
第9行出现 中国 次数: 3
第19行出现 中国 次数: 1
第34行出现 中国 次数: 1
第42行出现 中国 次数: 1



  • 6
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值