import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public final class StringCount { // 工具类中的方法都是静态方式访问的因此将构造器私有不允许创建对象(绝对好习惯) private StringCount() { throw new AssertionError(); } public static void main(String[] args) { StringCount.countWordInFile("G:\\a.txt", "b"); } /** * 统计给定文件中给定字符串的出现次数 * @param fileName 文件的路径及名字 * @param word 字符串 * @return 返回字符串出现的次数 */ public static int countWordInFile(String fileName, String word) { int counter = 0; FileReader fr = null; BufferedReader br = null; try { fr = new FileReader(new File(fileName)); br = new BufferedReader(fr); String line= null; while((line = br.readLine()) != null) { int index = -1; while(line.length() >= word.length() && (index = line.indexOf(word)) >= 0) { counter++; line = line.substring(index + word.length()); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); fr.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println(counter); return counter; } }
点赞 1

相关推荐

肖先生~:那年秋招闯进一位少年,人们都清楚:成功对他来说只是时间问题
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务