统计某个字符串在文件中出现的次数
2013-07-04 15:56
330 查看
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Demo4 { public int count(File file,String s){ int count = 0; BufferedReader br = null; try { br = new BufferedReader(new FileReader(file)); String temp; StringBuilder sb = new StringBuilder(); //读取文件 while((temp = br.readLine())!=null){ sb.append(temp); } String str = sb.toString(); //循环查找,找不到就终止循环 for (int i = 0; i < str.length(); i++) { int index = str.indexOf(s); if(index!=-1){ //找到以后把当前下标以前的字符串截取掉,然后用截取后的字符串循环判断 str = str.substring(index+1); count++; }else{ break; } } } catch (FileNotFoundException e) { System.out.println("找不到文件"); } catch (IOException e) { e.printStackTrace(); }finally{ try { if(br!=null)br.close(); } catch (IOException e) { e.printStackTrace(); } } return count; } public static void main(String[] args) { Demo4 d = new Demo4(); int count = d.count(new File("d://test.txt"), "I love china"); System.out.println(count); } }
相关文章推荐
- linux统计文件中字符串出现次数
- 利用Fork/Join框架来统计某个字符串在某个文件夹的文件中出现的次数
- shell统计文件里面特定字符串出现次数
- 自定义VBS脚本(统计在指定文件中搜索字符串出现的次数)
- 【shell】linux统计某一文件中字符串“sent ip”出现的次数
- 4.5统计字符串中数字和字母出现的次数,将结果写入文件
- Shell 统计文件里面特定字符串出现次数
- 统计这个字符串在这个文件中出现的次数。
- 【练手】写一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数
- Java实现——统计文件中字符串出现次数
- 统计一个字符串在文件中出现的次数
- 读取txt文件统计文章里"java"字符串出现的次数
- 统计字符串在文件中出现的次数 用系统命令实现
- 使用Linux命令统计文件指定列中字符串出现次数
- Java - 写一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数。
- 统计一文件中出现给定字符串的次数
- [置顶] Linux awk+uniq+sort 统计文件中某字符串出现次数并排序
- 统计文件里面某个字符串出现次数
- 从文件读取包含数字和字母字符串,统计每个字符出现的次数,将次数输出到另外一个文件
- 统计文件中某一字符串出现的次数