java实现 统计文件内容出现某字符串几次

package com.lzc.exception;

import java.io.*;

public class MyFileCycleStr {

	static String FilePath = "F:\\test.txt";	//文件路径
	static String specyficStr = "wq";	//特定字符
	
	public static void main(String[] args) throws IOException {
		int time = ReadFileInfo(FilePath,specyficStr);
		System.out.println("出现的次数是:"+time);
	}
	//返回文件内容中出现某字符几次
	private static int ReadFileInfo(String filePath,String specificStr) throws IOException {
		int time = 0;
		try {
		File file = new File(filePath);
		if(file.exists() && file.isFile()){
			InputStreamReader read = new InputStreamReader(new FileInputStream(file),"UTF-8");
			BufferedReader br = new BufferedReader(read); 
			String strTxt = null;
			while((strTxt = br.readLine()) != null){
				time += IndexOfMethod(strTxt,specificStr);
				//time += ReplaceMethod(strTxt,specificStr);
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return time;
		}
	
	/*
	 * indexOf函数方法实现
	 * 
	 *  1、 indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。 
	 *	2、 indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。 
	 *	3、 lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。 
	 *	4、 lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。
	 */
	private static int IndexOfMethod(String strTxt,String specificStr) {
		int time = 0;
		int index = 0;
		while(true){
			index = strTxt.indexOf(specificStr,index+1);
			if(index > 0){
				time++;
			}else{
				break;
			}
		}
		return time;
	}
	
	/*
	 * 替换法
	 * 通过将文本内容中特定字符串替换为新字符通过计算得出结果
	 */
	private static int ReplaceMethod(String strTxt,String specificStr) {
		String newStrTxt = strTxt.replace(specificStr, "");
		return (strTxt.length()-newStrTxt.length())/specificStr.length();
	}
	
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值