Created
March 20, 2018 09:24
-
-
Save kalgon/ac26faf66fac4998092bed5c18b7ea69 to your computer and use it in GitHub Desktop.
Seek for an array of bytes[]/chars[] in an OutputStream/Reader in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.Reader; | |
import java.io.StringReader; | |
public class StreamSeeker { | |
public static int seek(InputStream stream, byte[] bytes) throws IOException { | |
boolean[] checks = new boolean[bytes.length]; | |
for (int s = bytes.length, z = 0, i = 0, x; (x = stream.read()) != -1; z++, i = i == s - 1 ? 0 : i + 1) { | |
for (int j = 0; j < s; j++, i = i == 0 ? s - 1 : i - 1) { | |
if ((checks[i] = x == bytes[j] && (checks[i] || j == 0)) && j == s - 1) { | |
return z - s + 1; | |
} | |
} | |
} | |
return -1; | |
} | |
public static int seek(Reader reader, char[] chars) throws IOException { | |
boolean[] checks = new boolean[chars.length]; | |
for (int s = chars.length, z = 0, i = 0, x; (x = reader.read()) != -1; z++, i = i == s - 1 ? 0 : i + 1) { | |
for (int j = 0; j < s; j++, i = i == 0 ? s - 1 : i - 1) { | |
if ((checks[i] = x == chars[j] && (checks[i] || j == 0)) && j == s - 1) { | |
return z - s + 1; | |
} | |
} | |
} | |
return -1; | |
} | |
public static int seek(Reader reader, String string) throws IOException { | |
return seek(reader, string.toCharArray()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment