gpt4 book ai didi

java - 在二进制流中搜索字符串(作为 byte[])

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:05:32 27 4
gpt4 key购买 nike

您好团队,我正在尝试在二进制文件中找到字符串“Henry”并将该字符串更改为不同的字符串。仅供引用,该文件是对象序列化的输出。 Original Question here

我是搜索字节的新手,想象这段代码会搜索我的 byte[] 并交换它。但它并没有接近工作,它甚至找不到匹配项。

{
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 )

我想我每次读取 5 个字节时都需要移动 -4 个字节的位置。


宾果游戏,它现在找到了

    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[] searchedFor),它返回第一个匹配项匹配的索引,或 -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;
}
}

关于java - 在二进制流中搜索字符串(作为 byte[]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22234021/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com