gpt4 book ai didi

java - 在UTF-8流中间打开InputStreamReader

转载 作者:行者123 更新时间:2023-11-30 03:22:31 25 4
gpt4 key购买 nike

我正在使用可查找的输入流,它将流返回给我的特定位置。流中的底层数据使用 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);

关于java - 在UTF-8流中间打开InputStreamReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31008038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com