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();
}
}
java实现 统计文件内容出现某字符串几次
最新推荐文章于 2023-04-29 15:55:08 发布