从一个流中查找指定数组

import java.io.InputStream;




public class SeekInputStream 
{

/**
* 在流中查找,不适合查找全0数组,by samyou
* @param in
* @param key
* @return
*/
public static int seekBytes(InputStream in,byte[] key)
{
int lastSeekEnd = 0;
int result = -1;
byte buff[] = new byte[1000];
if(key.length > buff.length)
{
return -1;
}
try 
{
in.read(buff);
do{
result = normalSeek(buff, key);
if(result >= 0)
{
break;
}
System.arraycopy(buff, buff.length-key.length, buff, 0, key.length);
lastSeekEnd+=buff.length-key.length;
}
while( in.read(buff, key.length, buff.length-key.length) >0 );


catch (Exception e) 
{
e.printStackTrace();
try {
in.close();
} catch (Exception e2) {
}
return -1;
}
try {
in.close();
} catch (Exception e2) {
}
return result+lastSeekEnd;
}




/**
KMP查找算法
在一块buff中找
*/
private static int normalSeek(byte[] buff,byte[] key)
{
for(int i=0;i<buff.length -key.length;i++)
{
boolean seekSuccess = true;
for(int j=0;j<key.length;j++)
{
if(buff[i+j] != key[j])
{
seekSuccess  =false;
break;
}
}
if(seekSuccess)
{
return i;
}
}
return -1;
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值