繁体   English   中英

在UTF-8流的中间打开InputStreamReader

[英]Opening InputStreamReader in the middle of UTF-8 stream

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

这是我的代码片段

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

问题在于,如果position-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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM