查询文件中包含多少个指定的字符串

来源:互联网 发布:高中英语单词读音软件 编辑:程序博客网 时间:2024/05/17 01:11

最近在看一些面试题, 今天看了个操作文件的, 查询一个文件中包含多少个指定的字符串, 下面自己实现了一下:

/** * 查看一个文件中包含多少个指定字符串 * @param path 文件路径 * @param search 查询的字符串 * @return */private int searchCount(String path, String search) {int count = 0;InputStream is = null;try {is = new FileInputStream(new File(path));int c = 0;while((c=is.read()) !=-1){ // 是否读到有内容// 查询的第一个元素是否和当前读到的元素相等while(c == search.charAt(0)){// 从第二个元素开始继续判断后面的是否相等for (int i = 1; i < search.length(); i++) {c = is.read();// 不相等则退出循环if (c != search.charAt(i)) {break;}// 比较完了都还相等个数+1if (i == search.length() - 1) {count++;}}}}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (null != is) {try {// 关闭输入流is.close();} catch (IOException e) {e.printStackTrace();}}}return count;}

有些写得不对的地方望大家多多指导. 

0 0
原创粉丝点击