在二进制流中搜索字符串(作为byte []) [英] Search for a String (as an byte[]) in a binary stream
问题描述
Hi Team,我试图在二进制文件中找到一个StringHenry,并将String更改为另一个字符串。 FYI文件是对象序列化的输出。 此处的原始问题
我是新手搜索字节,并想象这段代码会搜索我的byte []并进行交换。但它没有接近工作它甚至找不到匹配。
Hi Team, I am trying to find a String "Henry" in a binary file and change the String to a different string. FYI the file is the output of serialisation of an object. Original Question here
I am new to searching bytes and imagined this code would search for my byte[] and exchange it. But it doesn't come close to working it doesn't even find a match.
{
byte[] bytesHenry = new String("Henry").getBytes();
byte[] bytesSwap = new String("Zsswd").getBytes();
byte[] seekHenry = new byte[bytesHenry.length];
RandomAccessFile file = new RandomAccessFile(fileString,"rw");
long filePointer;
while (seekHenry != null) {
filePointer = file.getFilePointer();
file.readFully(seekHenry);
if (bytesHenry == seekHenry) {
file.seek(filePointer);
file.write(bytesSwap);
break;
}
}
}
好的,我看到 bytesHenry == seekHenry
问题并将换成 Arrays.equals(bytesHenry,seekHenry)
Okay I see the bytesHenry==seekHenry
problem and will swap to Arrays.equals( bytesHenry , seekHenry )
我想每次读取5个字节时我需要移动-4个字节的位置。
I think I need to move along by -4 byte positions each time i read 5 bytes.
Bingo现在找到它
Bingo it finds it now
while (seekHenry != null) {
filePointer = file.getFilePointer();
file.readFully(seekHenry);;
if (Arrays.equals(bytesHenry,
seekHenry)) {
file.seek(filePointer);
file.write(bytesSwap);
break;
}
file.seek(filePointer);
file.read();
}
推荐答案
以下内容适用于您,请参阅方法 search(byte [] input,byte [] searchingFor)
,它返回第一个匹配项匹配的索引,或-1。
The following could work for you, see the method search(byte[] input, byte[] searchedFor)
which returns the index where the first match matches, or -1.
public class SearchBuffer {
public static void main(String[] args) throws UnsupportedEncodingException {
String charset= "US-ASCII";
byte[] searchedFor = "ciao".getBytes(charset);
byte[] input = "aaaciaaaciaojjcia".getBytes(charset);
int idx = search(input, searchedFor);
System.out.println("index: "+idx); //should be 8
}
public static int search(byte[] input, byte[] searchedFor) {
//convert byte[] to Byte[]
Byte[] searchedForB = new Byte[searchedFor.length];
for(int x = 0; x<searchedFor.length; x++){
searchedForB[x] = searchedFor[x];
}
int idx = -1;
//search:
Deque<Byte> q = new ArrayDeque<Byte>(input.length);
for(int i=0; i<input.length; i++){
if(q.size() == searchedForB.length){
//here I can check
Byte[] cur = q.toArray(new Byte[]{});
if(Arrays.equals(cur, searchedForB)){
//found!
idx = i - searchedForB.length;
break;
} else {
//not found
q.pop();
q.addLast(input[i]);
}
} else {
q.addLast(input[i]);
}
}
return idx;
}
}
这篇关于在二进制流中搜索字符串(作为byte [])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!