Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read InputStream until 4 specific chars to chars array

Tags:

java

How I can read in blocks from InputStream to chars[] until 4 specific chars?

I'm reading the input byte by byte, but complex condition of an exit from while turns out. And reading blocks more efficiently.

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++;
}
like image 268
VsSekorin Avatar asked Feb 07 '26 12:02

VsSekorin


1 Answers

Rather than reading character by character, create a larger buffer and use a variant of InputStream#read(buffer[], offset, length) to fill the buffer. The following function will efficiently determine the starting location of a 4 character match, or return -1 if none is found. The result then is the sequence of characters (in the buffer) from position 0 to 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;
}
like image 114
Ian Mc Avatar answered Feb 09 '26 08:02

Ian Mc