当前位置:   article > 正文

Java - 写一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数。

Java - 写一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数。

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程

代码如下:

  1. package chimomo.learning.java.code.file;
  2. import java.io.*;
  3. import java.nio.ByteBuffer;
  4. import java.nio.channels.FileChannel;
  5. /**
  6. * @author Created by Chimomo
  7. */
  8. public class FileUtil {
  9. private FileUtil() {
  10. throw new AssertionError();
  11. }
  12. /**
  13. * 统计给定文件中给定字符串的出现次数。
  14. *
  15. * @param filename 文件名
  16. * @param word 字符串
  17. * @return 字符串在文件中出现的次数
  18. */
  19. public static int countWordInFile(String filename, String word) {
  20. int counter = 0;
  21. try (FileReader fr = new FileReader(filename)) {
  22. try (BufferedReader br = new BufferedReader(fr)) {
  23. String line;
  24. while ((line = br.readLine()) != null) {
  25. int index;
  26. while (line.length() >= word.length() && (index = line.indexOf(word)) >= 0) {
  27. counter++;
  28. line = line.substring(index + word.length());
  29. }
  30. }
  31. }
  32. } catch (Exception ex) {
  33. ex.printStackTrace();
  34. }
  35. return counter;
  36. }
  37. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/45550
推荐阅读
相关标签
  

闽ICP备14008679号