java 文本关键字查找功能原理和代码

实现原理:

在使用String中indexOf()方法的时候,我们知道如果要是传入一个子字符串作为参数的话类似"from",则这个方法就返回此"from"子字符串第一次在此字符串中出现的位置,即返回此字符串中第一个"from"子字符串中字符"f"的位置。

  对于此方法忽然有点兴趣,因此我决定查看一下我当前使用的JDK1.7中的源码,其核心代码如下:
    static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        ......
        char first = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* 查找子字符串的第一个字符,如果第一个字符都没有出现,则此字符串中不包含这个子字符串 */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            /* 查找到第一个字符,则继续查找剩下的字符 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);

                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

  如上述代码中我写的注释那样,这个方法首先会查找子字符串的头字符在此字符串中第一次出现的位置,再以此位置的下一个位置作为起始,然后将子字符串的字符(头字符的下一个字符开始)依次和此字符串中字符进行比较,如果全部相等,则返回这个头字符在此字符串中的位置;如果有不相等的,则继续在剩下的字符串中查找这个子字符串的头字符,继续进行上面的过程,直到查找到子字符串或没有找到返回-1为止。

代码:

用JAVA实现对文本文件中的关键字进行搜索, 依据每一行,得到每一行中出现关键词的个数。使用java.io.LineNumberReader.java 进行行读取。示例如下:

一 实现类

[java]  view plain  copy
  1. package cn.youzi.test;  
  2.   
  3. import java.io.Closeable;  
  4. import java.io.File;  
  5. import java.io.FileReader;  
  6. import java.io.IOException;  
  7. import java.io.LineNumberReader;  
  8.   
  9. /** 
  10.  * 对文本文件的关键词进行搜索 
  11.  * @author Abel 
  12.  * 
  13.  */  
  14. public class TextFileSearch {  
  15.   
  16.     public void SearchKeyword(File file,String keyword) {  
  17.         //参数校验  
  18.         verifyParam(file, keyword);  
  19.           
  20.         //行读取  
  21.         LineNumberReader lineReader = null;  
  22.         try {  
  23.             lineReader = new LineNumberReader(new FileReader(file));  
  24.             String readLine = null;  
  25.             while((readLine =lineReader.readLine()) != null){  
  26.                 //判断每一行中,出现关键词的次数  
  27.                 int index = 0;  
  28.                 int next = 0;  
  29.                 int times = 0;//出现的次数  
  30.                 //判断次数  
  31.                 while((index = readLine.indexOf(keyword,next)) != -1) {  
  32.                     next = index + keyword.length();  
  33.                     times++;  
  34.                 }  
  35.                 if(times > 0) {  
  36.                     System.out.println("第"+ lineReader.getLineNumber() +"行" + "出现 "+keyword+" 次数: "+times);  
  37.                 }  
  38.             }  
  39.         } catch (IOException e) {  
  40.             e.printStackTrace();  
  41.         } finally {  
  42.             //关闭流  
  43.             close(lineReader);  
  44.         }  
  45.     }  
  46.   
  47.     /** 
  48.      * 参数校验 
  49.      *  
  50.      * <br> 
  51.      * Date: 2014年11月5日 
  52.      */  
  53.     private void verifyParam(File file, String keyword) {  
  54.         //对参数进行校验证  
  55.         if(file == null ){  
  56.             throw new NullPointerException("the file is null");  
  57.         }  
  58.         if(keyword == null || keyword.trim().equals("")){  
  59.             throw new NullPointerException("the keyword is null or \"\" ");  
  60.         }  
  61.           
  62.         if(!file.exists()) {  
  63.             throw new RuntimeException("the file is not exists");  
  64.         }  
  65.         //非目录  
  66.         if(file.isDirectory()){  
  67.             throw new RuntimeException("the file is a directory,not a file");  
  68.         }  
  69.           
  70.         //可读取  
  71.         if(!file.canRead()) {  
  72.             throw new RuntimeException("the file can't read");  
  73.         }  
  74.     }  
  75.       
  76.     /** 
  77.      * 关闭流 
  78.      * <br> 
  79.      * Date: 2014年11月5日 
  80.      */  
  81.     private void close(Closeable able){  
  82.         if(able != null){  
  83.             try {  
  84.                 able.close();  
  85.             } catch (IOException e) {  
  86.                 e.printStackTrace();  
  87.                 able = null;  
  88.             }  
  89.         }  
  90.     }  
  91.   
  92. }  

二 调用

[java]  view plain  copy
  1. package cn.youzi.test;  
  2.   
  3. import java.io.File;  
  4.   
  5. public class TextFileSearchTest {  
  6.   
  7.     public static void main(String[] args) {  
  8.   
  9.         TextFileSearch search = new TextFileSearch();  
  10.         search.SearchKeyword(new File("E:\\testDir\\news.txt"), "中国");  
  11.     }  
  12.   
  13. }  

结果 为:

[plain]  view plain  copy
  1. 第3行出现 中国 次数: 3  
  2. 第5行出现 中国 次数: 4  
  3. 第7行出现 中国 次数: 1  
  4. 第9行出现 中国 次数: 3  
  5. 第19行出现 中国 次数: 1  
  6. 第34行出现 中国 次数: 1  
  7. 第42行出现 中国 次数: 1  

猜你喜欢

转载自blog.csdn.net/csdnliuxin123524/article/details/80208207