读取InputStream直到4个特定的字符到字符数组

时间:2018-04-04 21:11:53

标签: java

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

我正在逐字节地读取输入,但是从while退出的复杂条件变成了。并且更有效地阅读块。

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++;
}

2 个答案:

答案 0 :(得分:2)

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

// 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;
}

答案 1 :(得分:0)

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

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;
        }
    }
}

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