我试图对包含字符串和整数的二进制文件中的字符串执行二进制搜索。 我尝试的代码如下:
// 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
单词Vice存在于二进制文件中,尽管从未找到过。我也打印了我的线条,我得到了这些结果:RESULTS