public class StringCountInFile {
public static void main(String[] args) {
//获取当前项目的路径
//System.out.println(System.getProperty("user.dir"));
System.out.println(countStrInFile2("src/niuke/test.txt", "o"));
}
/**
* 统计指定字符串在文件中出现的次数
* 正则表达式
* 是区分大小写的
* @param filename
* @param str
*/
public static int countStrInFile(String filename,String str){
int count = 0;
//读取指定路径的文件 fileReader
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
String line ;
StringBuffer fileStr = new StringBuffer();
while ((line = br.readLine()) != null){
fileStr = fileStr.append(line);
}
String patten = ".*"+str+".*";
while (true){
//当字符串中没有str字串,退出循环
if (Pattern.matches(patten,fileStr)){
//次数加1
count ++;
//从大串中删除字串
int start = fileStr.indexOf(str);
//左闭右开
fileStr.delete(start,start+str.length());
}
else {
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//返回次数
return count;
}
/**
* 统计指定字符串在文件中出现的次数
*
* @param filename
* @param str
*/
public static int countStrInFile2(String filename,String str){
int count2 = 0;
try {
//创建输入缓冲流
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
//创建可变字符串
StringBuilder sb = new StringBuilder();
//每一次读取一行,加入到可变字符串
String line;
while ((line = br.readLine()) != null){
sb = sb.append(line);
}
//每次找到一个就从大字符串中删除
while (sb.indexOf(str) != -1){
count2 ++;
int start = sb.indexOf(str);
sb.delete(start,start+str.length());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return count2;
}
}
统计文件中指定字符串的个数
最新推荐文章于 2022-04-15 17:44:23 发布