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

java 文本关键字查找功能原理和代码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  

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/106117.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • JAVA版位图排序(算法珠玑开篇的例子)

    JAVA版位图排序(算法珠玑开篇的例子)

    2021年5月8日
    128
  • 编码的奥秘_生活中运用数字编码的例子有哪些

    编码的奥秘_生活中运用数字编码的例子有哪些摩尔斯电码:由萨谬尔摩尔斯发明观察可得E,T:只有一个滴或哒2^1I,A,N,M:是有两个滴答组成2^2以此类推三个滴答可以组成8个字母2^3四个滴答可以组成16个字母2^4这样就

    2022年8月4日
    5
  • java定时器实例_Java定时器小实例

    java定时器实例_Java定时器小实例有时候,我们需要在Java中定义一个定时器来轮询操作,比如每隔一段时间查询、删除数据库中的某些数据等,下面记录一下一种简单实现方式1,首先新建一个类,类中编写方法来实现业务操作publicclassMailQuartz{@AutowiredprivateMailServiceImplsendMail;@AutowiredprivateTimerServiceImpltimerService…

    2022年9月18日
    5
  • msys2安装与使用_mingw使用教程

    msys2安装与使用_mingw使用教程一、安装官方下载地址http://www.msys2.org/指定好安装路径(一般D根目录即可),一路下一步就好。二、配置国内镜像、设置窗体修改颜色使用[清华大学开源软件镜像站]中的地址,修

    2022年8月6日
    7
  • WebService接口

    WebService接口这是我在做对外部系统推送数据时自己写的WebService推送接口工具类,有几点需要注意1、我们调用对方的WebService接口,对方会给一个WebService接口的地址,供我们访问:http:

    2022年7月1日
    17
  • AAA认证及RADIUS配置「建议收藏」

    AAA认证及RADIUS配置「建议收藏」AAA认证及RADIUS配置AAA简介AAA是Authentication,AuthorizationandAccounting(认证、授权和计费)的简称,它提供了一个对认证、授权和计费这三种安全功能进行配置的一致性框架,实际上是对网络安全的一种管理。这里的网络安全主要是指访问控制,包括:.哪些用户可以访问网络服务器。.具有访问权的用户可以得到…

    2022年5月25日
    63

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号