我正在尝试编写一个程序,我可以:
- 加载文件
- 输入扫描数据的起始位置和起始偏移地址
- 扫描该偏移范围以搜索特定的字节序列(例如“05805A6C”)
- 检索每个匹配项的偏移量并将其写入 .txt 文件
i66.tinypic.com/2zelef5.png
如图所示,我需要在文件中搜索“05805A6C”,然后将偏移量“0x21F0”打印到 .txt 文件。
我为此使用 Java Swing。到目前为止,我已经能够将文件作为字节数组[]加载。但我还没有找到一种方法来搜索特定的字节序列,也没有找到在一系列偏移量之间设置搜索的方法。
这是我的代码,用于打开文件并将其读入字节数组[]
public class Read {
static public byte[] readBytesFromFile () {
try {
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
FileInputStream input = new FileInputStream(chooser.getSelectedFile());
byte[] data = new byte[input.available()];
input.read(data);
input.close();
return data;
}
return null;
}
catch (IOException e) {
System.out.println("Unable to read bytes: " + e.getMessage());
return null;
}
}
}
以及我尝试在字节中搜索的代码。
byte[] model = Read.readBytesFromFile();
String x = new String(model);
boolean found = false;
for (int i = 0; i < model.length; i++) {
if(x.contains("05805A6C")){
found = true;
}
}
if(found == true){
System.out.println("Yes");
}else{
System.out.println("No");
}
最佳答案
这是一种在字节数组中搜索字节序列的防弹1方法:
public boolean find(byte[] buffer, byte[] key) {
for (int i = 0; i <= buffer.length - key.length; i++) {
int j = 0;
while (j < key.length && buffer[i + j] == key[j]) {
j++;
}
if (j == key.length) {
return true;
}
}
return false;
}
对于大规模搜索,有更有效的方法来做到这一点;例如使用 Boyer-Moore 算法。然而:
将字节数组转换为字符串并使用 Java 字符串搜索并不更有效,而且它可能很脆弱,具体取决于将字节转换为字符串时使用的编码。
将字节数组转换为十六进制编码的字符串效率更低……而且内存消耗很大……但如果您有足够的内存,则不会脆弱。 (在进行转换时,您可能需要最多 5 倍于文件大小的内存...)
1 - 防炸弹,以任何错误为模:-)
关于java - 如何在bin文件的字节数组[]中搜索字节序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35248973/