`

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

io 
阅读更多
public int countWords(String file, String find) {
		int count = 0;
		try {
			Reader in = new FileReader(file);
			System.out.println(in.read());
			System.out.println(find.charAt(0));
			int c;
			while ((c = in.read()) != -1) {
				while (c == find.charAt(0)) {
					if (find.length() == 1) {
						count++;
						c = in.read();
					}// 这是我添加的,不然就是死循环 用"a"测试的时候
					for (int i = 1; i < find.length(); i++) {
						c = in.read();
						if (c != find.charAt(i))
							break;
						if (i == find.length() - 1)
							count++;
					}
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// FileReader()返回的字节流是以平台编码的流
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return count;
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics