需求:读取txt文件 统计“java”出现的次数(大小写不敏感)
package com.wh.test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; /** * @category需求:统计附件 <Think in Java中文版 > 中“java”出现的次数(大小写不敏感): * @version 2017年6月1日 * @author forever-2h */ public class Work2 { public static void main(String[] args) { fread("D:\MyEclipse\worktest\src\Think in Java中文版.txt"); } // 读取文件: public static void fread(String fileurl) { File file = new File(fileurl); BufferedReader bfr = null; int count = 0; try { bfr = new BufferedReader(new FileReader(file)); String tem = null; String value = "java"; while ((tem = bfr.readLine()) != null) { int index = -1; while (tem.length() >= value.length() && (index = tem.toLowerCase().indexOf(value)) >= 0) {// 大小写不敏感 count++; tem = tem.substring(index + value.length()); } } System.out.println("文中java(大小写不敏感)出现次数为:" + count); } catch (Exception e) { System.err.println("文件读取错误"); } finally { try { if (bfr != null) { bfr.close(); } } catch (Exception e2) { System.err.println("文件关闭错误"); } } } }