1. 程式人生 > >寫一個方法,輸入一個檔名和一個字串,統計這個字串在這個檔案中出.........

寫一個方法,輸入一個檔名和一個字串,統計這個字串在這個檔案中出.........

寫一個方法,輸入一個檔名和一個字串,統計這個字串在這個檔案中出現的次數.

這是一個常見的演算法提問,網上搜索結果不是很滿意。自己解決了一下:

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()來處理檔案輸入,是它能自由操作檔案指標,方便讀取~