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

标签 java encoding utf-8

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

相关文章:

php - 使用 imagettftext() 时如何处理字体文件不支持的字符?

java - findviewbyid 给出意外的空指针异常

java - 音频文件编解码

c# - 在 C# .NET 中编码非 ascii 字符

c# - 如何在 C#.NET、PHP 和 MySQL 之间获得通用的编码?

ruby - 如何将 UTF-8 支持添加到 Ruby 中的排序(包括 ł 字符,而不影响可移植性)?

parsing - 在haskell中快速解析大型utf-8文本文件

java - freebase mqlread 查询异常

java - 迭代列表的列表

java - 在 Serenity 上设置 PhantomJS webDriver