【问题标题】:Fastest way to find a string in a text file with java使用java在文本文件中查找字符串的最快方法
【发布时间】:2011-03-28 14:44:37
【问题描述】:

检查文件是否包含某个字符串或数字的最快方法是什么?

【问题讨论】:

标签: java text find pattern-matching


【解决方案1】:

查看 JDK (See official documentation) 附带的 Scanner 类。您将能够跳过输入的某些部分(在本例中为文本文件)并匹配您想要的正则表达式。我不确定这是否是最有效的方法,但可以肯定 - 它非常简单。你也可以看看this example,它会帮助你入门。

【讨论】:

    【解决方案2】:

    未尝试过,但可能最快的机制是首先获取您的搜索键并像文件一样对其进行编码。

    例如,如果您知道文件是 UTF-8,则获取您的密钥并将其从字符串(它是 UTF-16)编码为 UTF-8 字节数组。这很重要,因为通过对文件表示进行编码,您只需对密钥进行编码。使用标准 Java 阅读器则相反——将文件转换为 UTF-16。

    现在您有了正确的密钥(以字节为单位),使用 NIO 为文件创建一个MappedByteBuffer。这会将文件映射到虚拟内存空间。

    最后,实现Boyer-Moore algorithm 进行字符串搜索,通过映射区域使用键的字节与文件的字节进行对比,

    可能有一种更快的方法,但这解决了在 Java 中搜索文本文件的大部分问题。它利用 VM 来避免复制文件的大块,并且跳过了将文件中的任何编码转换为 Java 内部使用的 UTF-16 的转换步骤。

    【讨论】:

      【解决方案3】:

      查看以下算法:

      或者如果你想找到一组字符串中的一个:

      【讨论】:

        【解决方案4】:

        我在 MIMEParser 中发现的最好的实现: https://github.com/samskivert/ikvm-openjdk/blob/master/build/linux-amd64/impsrc/com/sun/xml/internal/org/jvnet/mimepull/MIMEParser.java

        /**
         * Finds the boundary in the given buffer using Boyer-Moore algo.
         * Copied from java.util.regex.Pattern.java
         *
         * @param mybuf boundary to be searched in this mybuf
         * @param off start index in mybuf
         * @param len number of bytes in mybuf
         *
         * @return -1 if there is no match or index where the match starts
         */
        
        private int match(byte[] mybuf, int off, int len) {
        

        还需要:

        private void compileBoundaryPattern();
        

        【讨论】:

          猜你喜欢
          • 2010-11-17
          • 1970-01-01
          • 2014-02-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-25
          相关资源
          最近更新 更多