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;
	}
}