首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将InputStream读入字符数组,直到4个特定字符

将InputStream读入字符数组,直到4个特定字符
EN

Stack Overflow用户
提问于 2018-04-04 21:11:52
回答 2查看 304关注 0票数 2

如何读取从InputStreamchars[]的块,直到4个特定字符?

我正在逐字节读取输入字节,但是从while退出的复杂条件却变成了事实。阅读更有效率。

代码语言:javascript
复制
int p0 = stream.read(),
    p1 = stream.read(),
    p2 = stream.read(),
    p3 = stream.read();
while (!(p0 == a && p1 == b && p2 == c && p3 == d)) {
    result[i] = (char) p0;
    p0 = p1;
    p1 = p2;
    p2 = p3;
    p3 = stream.read();
    i++;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-04 22:21:35

与其逐字符读取,不如创建一个更大的缓冲区,并使用InputStream#read(buffer[], offset, length)的一个变体来填充缓冲区。以下函数将有效地确定4个字符匹配的起始位置,如果没有找到,则返回-1。然后,result是从位置0到getIndex(buf)-1的字符序列(在缓冲区中)。

代码语言:javascript
复制
// Will determine the starting index of the 4 specific characters (or -1)
int getIndex(char buf[]) {

    char c4='z';
    char c3='y';
    char c2='x';
    char c1='w';

    int tail = 3;
    while (tail < buf.length) {
        if (buf[tail] == c4 && buf[tail-1] == c3 && buf[tail-2] == c2 && buf[tail-3] == c1)
            return tail-3;
        tail++;
    }
    return -1;
}
票数 2
EN

Stack Overflow用户

发布于 2018-04-04 21:39:16

从流中读取字符,直到给定的特定字符:

代码语言:javascript
复制
void readWhile(InputStream stream, char[] specificChars) throws IOException {
    InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
    char[] buffer = new char[specificChars.length];
    while (reader.read(buffer) != -1) {
        if (Arrays.equals(buffer, specificChars)) {
            // the specific chars were found
            return;
        }
    }
}

为了读取实际字符,必须使用字符集对流字节进行解码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49660510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档