[英]Opening InputStreamReader in the middle of UTF-8 stream
I am using a seekable InputStream which returns the stream to me at a specific position. 我正在使用可搜索的InputStream,它在特定位置将流返回给我。 The underlying data in the stream is encoded with UTF-8.
流中的基础数据使用UTF-8编码。 I want to open this stream using inputStreamReader and read one character at a time.
我想使用inputStreamReader打开此流并一次读取一个字符。
Here is my code snippet 这是我的代码片段
inputStream.seek(position-1);
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
The problem is that if position-1 could be pointing to the middle of a multi-byte UTF-8 sequence. 问题在于,如果position-1可能指向多字节UTF-8序列的中间。 How can I detect that make sure it starts from a new UTF-8 encoded sequence?
如何检测以确保它从新的UTF-8编码序列开始? Thanks in advance.
提前致谢。
Assuming you can reposition the stream whenever you want, you can simply read bytes while the top two bits are "10". 假设您可以随时重新定位流,则只需读取字节,而高两位为“ 10”即可。 So something like:
所以像这样:
// 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.