我正在从tcp套接字读取数据流。所有这些数据都被发送到一个字节数组中:
DataInputStream in = new DataInputStream(mysource.getInputStream());
FileOutputStream output = new FileOutputStream(path);
int len;
byte buffer[] = new byte [8192];
while(len = in.read(buffer)) !=-1){
output.write(buffer);
}
output.close();
在读取流时,我想检测一个随机重复的特定4字节patern。
我尝试在保存数据后使用for
语句来遍历所有数据,但这种解决方案效率很低。
有什么方法可以实时做到这一点吗?
/**
* Knuth-Morris-Pratt Algorithm for Pattern Matching
*/
class KMPMatch {
/**
* Finds the first occurrence of the pattern in the text.
*/
public int indexOf(byte[] data, byte[] pattern) {
int[] failure = computeFailure(pattern);
int j = 0;
if (data.length == 0) return -1;
for (int i = 0; i < data.length; i++) {
while (j > 0 && pattern[j] != data[i]) {
j = failure[j - 1];
}
if (pattern[j] == data[i]) { j++; }
if (j == pattern.length) {
return i - pattern.length + 1;
}
}
return -1;
}
/**
* Computes the failure function using a boot-strapping process,
* where the pattern is matched against itself.
*/
private int[] computeFailure(byte[] pattern) {
int[] failure = new int[pattern.length];
int j = 0;
for (int i = 1; i < pattern.length; i++) {
while (j > 0 && pattern[j] != pattern[i]) {
j = failure[j - 1];
}
if (pattern[j] == pattern[i]) {
j++;
}
failure[i] = j;
}
return failure;
}
}
从这里:使用Java 搜索二进制文件中的字节序列