写一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出......
写一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数.
这是一个常见的算法提问,网上搜索结果不是很满意。自己解决了一下:
?
package com.xforward.ccf;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.util.Arrays;
public class CopyOfFile_test_count {
?public static void main(String[] args) {
??try {
???int count = countWords_ccf("D:\\test.txt", "aa");
???System.out.println(count);
//???count = countWords("D:\\test.txt", "a");
//???System.out.println(count);
??} catch (Exception e) {
???e.printStackTrace();
??}
?}
?/*
? *这是网上搜索的东东,不是很理想~
? */
?public static int countWords(String file, String find) throws Exception {
??int count = 0;
??Reader in = new FileReader(file);// FileReader()返回的字节流是以平台编码的流
??int c;
??while ((c = in.read()) != -1) {
???while (c == find.charAt(0)) {
????if(find.lenth()==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++;
????}
???}
??}
??return count;
?}
?
?public static int countWords_ccf(String file, String find) throws Exception {
??int count = 0;
??byte[] bytes = find.getBytes();
??int find_l = bytes.length;
??byte[] bytes_f = new byte[find_l];
??RandomAccessFile in = new RandomAccessFile(file, "rw");//返回的字节流是以平台编码的流
??int bytes_f_l = 0;
??int read_mark = 0;
??while (-1 != (bytes_f_l = in.read(bytes_f))) {// 这里不用担心~读到的数据是-1
???if (bytes_f_l < find_l) {
????break;
???}
???if (Arrays.equals(bytes, bytes_f)) {
????count++;
???}
???in.seek(++read_mark);
??}
??return count;
?}
}
?
----------------------------------------测试文件内容-----------------------------------------------
D:\test.txt
?
好aaadsaaaa
?
总结:<1>在Java I/O 中,充分地考虑编码问题是很重要的一个方向,如果搞不清原理的话是很费神的;<2>之所以应用RandomAccessFile()来处理文件输入,是它能自由操作文件指针,方便读取~