在 UTF-8 流中间打开 InputStreamReader

Opening InputStreamReader in the middle of UTF-8 stream

我正在使用可搜索的 InputStream,它 returns 在特定位置向我发送流。流中的基础数据使用 UTF-8 编码。我想使用 inputStreamReader 打开这个流并一次读取一个字符。

这是我的代码片段

inputStream.seek(position-1);
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");

问题是位置 1 可能指向多字节 UTF-8 序列的中间。我如何检测以确保它从新的 UTF-8 编码序列开始?提前致谢。

假设您可以随时重新定位流,您可以简单地读取前两位为“10”的字节。所以像:

// InputStream doesn't actually have a seek method, but I'll assume you're using
// a subclass which does...
inputStream.seek(position);
while (true) {
    int nextByte = inputStream.read();
    if (nextByte == -1 || (nextByte & 0xc0) != 0xc0) {
       break;
    }
    position++;
}
// Undo the last read, effectively
inputStream.seek(position);
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);