给定一个文件名,和字符串,统计字符中在文件中出现的次数

package com.test.read;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadText {
public static void main(String[] args) {

String path="C:\\Users\\Administrator\\Desktop\\11.txt";
File file=new File(path);
String str="aa";
int count=0;
try {
count = readSize(file, str);
} catch (IOException e) {

e.printStackTrace();
}
System.out.println("次数"+count);
}

public static int readSize(File file,String str) throws IOException {
BufferedReader br=new BufferedReader(new FileReader(file));
StringBuffer sbuffer=new StringBuffer();


//循环获取文本中的字符串
//逐行获取文本的字符
while(true) {
String line=br.readLine();
if(line==null) {
break;
}
sbuffer.append(line);
}
String resultStr=sbuffer.toString();
int count = 0;
int index = 0;
while (true) {
index = resultStr.indexOf(str , index + 1);
if (index > 0) {
count++;
}else {
break;
}
}
br.close();
return count;

}
}

猜你喜欢

转载自www.cnblogs.com/woshuaile/p/9564125.html