二进制文件中的二进制搜索

问题描述 投票:1回答:0

我正在尝试对包含字符串和整数的二进制文件中的字符串执行二进制搜索。 我尝试的代码如下:

 // open the file for reading
        RandomAccessFile raf = new RandomAccessFile("myfile","r");
        String searchValue = "Vice";
        int lineSize = 22;
        int numberOfLines = (int) (raf.length() / lineSize);

        // perform the binary search...
        byte[] lineBuffer = new byte[lineSize];
        int bottom = 0;
        int top = numberOfLines;
        int middle;
        while (bottom <= top){
          middle = (bottom+top)/2;
          raf.seek(middle*lineSize); // jump to this line in the file
          raf.read(lineBuffer); // read the line from the file
          String line1 = new String(lineBuffer); // convert the line to a String
          System.out.println("Line:"+line1);
          //int comparison = line1.compareTo(searchValue);
          int comparison = comparator.compare(line1, searchValue);
          if (comparison == 0){ //strings are lexicographically equal. Could check for actual equality here.
            System.out.println("FOUND");
            break;
            }
          else if (comparison < 0){
            bottom = middle + 1;
            }
          else { 
            top = middle - 1;
            }
          }

        raf.close(); // close the file when you're finished

尽管从未发现二进制文件中存在“恶习”一词。 我也打印了行,得到了以下结果: 结果

java file search binary binary-search
© www.soinside.com 2019 - 2024. All rights reserved.