有没有一种方法可以有效地搜索 InputStream 上的 2 个固定字节?
背景
我必须处理 Android 上的多部分 Http 流量。 (来自 IP 网络摄像头的动态 JPEG)。
我已经在 anddev.org 上找到了一些类来处理它。现在我做了一些性能改进。要找到 JPEG 的开头,我需要在 InputStream 中找到 JPEG (SOI=FFD8) 的魔数(Magic Number)。
最佳答案
由于您不知道这 2 个字节在流中的什么位置,因此您必须查看整个输入。这意味着,您的表现至少是线性的。两个线性查找两个字节很简单:
static long search(InputStream inputStream) throws IOException {
BufferedInputStream is = new BufferedInputStream(inputStream);
int previous = is.read(read);
long pos = 0;
int current;
while((current = is.read()) != -1) {
pos++;
if(previous == 0xff && current == 0xd8) {
return pos;
}
last = current;
}
throw new RuntimeException("There ain't no pic in here.");
}
关于java - 在 InputStream 中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6958845/