Java统计一个字符串在一个文件中出现的次数,具体代码如下:
package demo;
import java.io.FileReader;
import java.io.Reader;
/**
* 统计一个字符串在文件中出现的次数
*
* @author 四个空格-https://www.4spaces.org
*
*/
public class CountTimes {
/**
*
* @param file
* @param find
* @return
* @throws Exception
*/
public int countWords(String file, String find) throws Exception {
int count = 0;
try {
Reader in = new FileReader(file);
int c;
while ((c = in.read()) != -1) {
while (c == find.charAt(0)) {
for (int i = 1; i < find.length(); i++) {
c = in.read();
if (c != find.charAt(i)) {
break;
}
if (i == find.length() - 1) {
count++;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
public static void main(String[] args) {
String file = "D:/report_data2.txt";
String find = "down";
CountTimes ct = new CountTimes();
try {
int n = ct.countWords(file, find);
System.out.println(n);
} catch (Exception e) {
e.printStackTrace();
}
}
}