java - 在 InputStream 中搜索

标签 java android search performance inputstream

有没有一种方法可以有效地搜索 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/

相关文章:

java - 当索引未知时如何更改数组中的一个位置?

java - org.jsoup.select.Selector$SelectorParseException : Could not parse query

java - JSONObject 在使用字符串实例化后返回非空值 "null"

php - 在 Laravel 中执行此查询的最佳方式是什么?

php - 查询搜索 Laravel 5

arrays - 在字符串数组中查找特定字符/字母的算法?

java - 在标准变量上使用常量是否使用更少的内存?

java - Jetty servlet如何轻松操作HTML文件

android - 在主屏幕上创建 Android 应用程序的快捷方式

android - onBindViewHolder 绑定(bind) View 不一致