使用 RandomAccessFile 读取单个 UTF-8 字符

Reading a single UTF-8 character with RandomAccessFile

我设置了顺序扫描器,其中指向我的文件的 RandomAccessFile 能够通过以下方法读取单个字符:

public char nextChar() {
    try {
        seekPointer++;
        int i = source.read();
        return i > -1 ? (char) i : '[=10=]'; // INFO: EOF character is -1.
    } catch (IOException e) {
        e.printStackTrace();
    }
    return '[=10=]';
}

seekPointer 只是我程序的参考,但该方法将 source.read() 存储在 int 中,然后将 returns 转换为 char 如果它不是文件的末尾。但是我收到的这些字符是 ASCII 格式的,事实上它太糟糕了,我什至不能使用 ç.

这样的符号

有没有一种方法可以接收 单个 字符,即 UTF-8 格式或至少允许 ASCII 字符集以外的标准化内容?

我知道我可以使用 readUTF() 但是 returns 整行作为字符串,这不是我想要的。

此外,我不能简单地使用另一个流 reader,因为我的程序需要一个 seek(int) 函数,允许我在文件中来回移动。

我不完全确定你想做什么,但让我给你一些可能有帮助的信息。

UTF-8 编码将字符表示为 1、2、3 或 4 个字节,具体取决于字符的 Unicode 值。

  • 对于字符 0x00-0x7F,UTF-8 将字符编码为单个字节。这非常有用 属性 因为如果您只处理 7 位 ASCII 字符,UTF-8 和 ASCII 编码是相同的。
  • 对于字符0x80-0x7FF,UTF-8使用2个字节:第一个字节是二进制110,后面是字符的高5位,第二个字节是二进制10,后面是字符的低6位.
  • 3字节编码和4字节编码与2字节编码类似,只是3字节编码的第一个字节以1110开头,4字节编码的第一个字节以11110开头。
  • 有关所有详细信息,请参阅 Wikipedia

现在这可能看起来很复杂,但结果是这样的:您可以读取 UTF-8 文件中的 any 字节,并知道您是否正在查看一个独立的字符、多字节字符的第一个字节或多字节字符的其他字节之一。

如果您读取的字节以二进制 0 开头,则您正在查看 single-byte 字符。如果它以 110、1110 或 11110 开头,则多字节字符的第一个字节分别为 2、3 或 4 个字节。如果它以 10 开头,则它是多字节字符的后续字节之一;向后扫描以找到它的开头。

所以如果你想让你的调用者寻找文件中的任意随机位置并在那里读取 UTF-8 字符,你可以只应用上面的算法来找到该字符的第一个字节(如果它不是一个在指定位置),然后读取并解码该值。

有关从源字节解码 UTF-8 的方法,请参阅 Java 字符集 class。可能有更简单的方法,但 Charset 会起作用。

更新:此代码应处理 1 字节和 2 字节 UTF-8 的情况。完全没有测试,YMMV。

for (;;) {
    int b = source.read();
    // Single byte character starting with binary 0.
    if ((b & 0x80) == 0)
        return (char) b;
    // 2-byte character starting with binary 110.
    if ((b & 0xE0) == 0xC0)
        return (char) ((b & 0x1F) << 6 | source.read() & 0x3F);
    // 3 and 4 byte encodings left as an exercise...
    // 2nd, 3rd, or 4th byte of a multibyte char starting with 10. 
    // Back up and loop.
    if ((b & 0xC0) == 0xF0) 
        source.seek(source.getFilePosition() - 2);
}

我不会为 seekPointer 而烦恼。 RandomAccessFile 知道它是什么;只需在需要时调用 getFilePosition。

java.io.DataInputStream.readUTF(DataInput) 中的 case 语句你可以推导出类似

public static char readUtf8Char(final DataInput dataInput) throws IOException {
    int char1, char2, char3;

    char1 = dataInput.readByte() & 0xff;
    switch (char1 >> 4) {
        case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
            /* 0xxxxxxx*/
            return (char)char1;
        case 12: case 13:
            /* 110x xxxx   10xx xxxx*/
            char2 = dataInput.readByte() & 0xff;
            if ((char2 & 0xC0) != 0x80) {
                throw new UTFDataFormatException("malformed input");
            }
            return (char)(((char1 & 0x1F) << 6) | (char2 & 0x3F));
        case 14:
            /* 1110 xxxx  10xx xxxx  10xx xxxx */
            char2 = dataInput.readByte() & 0xff;
            char3 = dataInput.readByte() & 0xff;
            if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
                throw new UTFDataFormatException("malformed input");
            }
            return (char)(((char1 & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
        default:
            /* 10xx xxxx,  1111 xxxx */
            throw new UTFDataFormatException("malformed input");
    }
}

请注意,RandomAccessFile 实现了 DataInput,因此您可以将其传递给上述方法。在为第一个字符调用它之前,您需要读取一个代表 UTF 字符串长度的无符号 short。

注意这里使用的编码是modified-UTF-8,在DataInput的Javadoc中有描述

根据 Willis Blackburn 的回答,我可以简单地进行一些整数检查以确保它们超过一定数量,以获得我需要提前检查的字符数量。

根据以下判断table:

first byte starts with 0                         1 byte char
first byte starts with 10    >= 128 && <= 191    ? byte(s) char
first byte starts with 11        >= 192          2 bytes char
first byte starts with 111       >= 224          3 bytes char
first byte starts with 1111      >= 240          4 bytes char

我们可以通过将它与中间列中的数字进行比较来检查从 RandomAccessFile.read() 中读取的整数,这些数字实际上只是一个字节的整数表示。这使我们能够完全跳过字节转换,从而节省时间。

以下代码将从 RandomAccessFile 中读取一个字符,byte-length 为 1-4:

int seekPointer = 0;
RandomAccessFile source; // initialise in your own way

public void seek(int shift) {
    seekPointer += shift;
    if (seekPointer < 0) seekPointer = 0;
    try {
        source.seek(seekPointer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private int byteCheck(int chr) {
    if (chr == -1) return 1; // eof
    int i = 1; // theres always atleast one byte
    if (chr >= 192) i++; // 2 bytes
    if (chr >= 224) i++; // 3 bytes
    if (chr >= 240) i++; // 4 bytes
    if (chr >= 128 && chr <= 191) i = -1; // woops, we're halfway through a char!
    return i;
}

public char nextChar() {
    try {
        seekPointer++;
        int i = source.read();

        if (byteCheck(i) == -1) {
            boolean malformed = true;
            for (int k = 0; k < 4; k++) { // Iterate 3 times.
                // we only iterate 3 times because the maximum size of a utf-8 char is 4 bytes.
                // any further and we may possibly interrupt the other chars.
                seek(-1);
                i = source.read();
                if (byteCheck(i) != -1) {
                    malformed = false;
                    break;
                }
            }
            if (malformed) {
                seek(3);
                throw new UTFDataFormatException("Malformed UTF char at position: " + seekPointer);
            }
        }

        byte[] chrs = new byte[byteCheck(i)];
        chrs[0] = (byte) i;

        for (int j = 1; j < chrs.length; j++) {
            seekPointer++;
            chrs[j] = (byte) source.read();
        }

        return i > -1 ? new String(chrs, Charset.forName("UTF-8")).charAt(0) : '[=11=]'; // EOF character is -1.
    } catch (IOException e) {
        e.printStackTrace();
    }
    return '[=11=]';
}