Android从文本文件中获取UTF的UTFDataFormatException读取

时间:2012-06-26 15:15:03

标签: android utf datainputstream

我在我的Android应用程序的事件日志中注意到我收到了UTFDataFormatException错误。我正在阅读的文件是由我的应用程序编写的,虽然它存储有关用户故事的信息,但它可以包含任何类型的字符/字符串。我想知道读/写某些字符是否有问题?

我写道:

dos.writeUTF(myJSONString);

我在阅读时使用:

textJSONString = dis.readUTF();

我记录的一些错误堆栈跟踪是:

class: class java.io.UTFDataFormatException

message: bad second or third byte at 1795

    java.io.charset.ModifiedUtf8.decode(ModifiedUtf8.java:53) 
java.io.DataInputStream.decodeUTF(DataInputStream.java:444) 
java.io.DataInputStream.decodeUTF(DataInputStream.java:438) 
java.io.DataInputStream.readUTF(DataInputStream.java:433)...

我查找了解码方法的来源,但我不明白发生了什么/为什么会失败:

public static String decode(byte[] in, char[] out, int offset, int utfSize) throws UTFDataFormatException {
        int count = 0, s = 0, a;
        while (count < utfSize) {
            if ((out[s] = (char) in[offset + count++]) < '\u0080') {
                s++;
            } else if (((a = out[s]) & 0xe0) == 0xc0) {
                if (count >= utfSize) {
                    throw new UTFDataFormatException("bad second byte at " + count);
                }
                int b = in[offset + count++];
                if ((b & 0xC0) != 0x80) {
                    throw new UTFDataFormatException("bad second byte at " + (count - 1));
                }
                out[s++] = (char) (((a & 0x1F) << 6) | (b & 0x3F));
            } else if ((a & 0xf0) == 0xe0) {
                if (count + 1 >= utfSize) {
                    throw new UTFDataFormatException("bad third byte at " + (count + 1));
                }
                int b = in[offset + count++];
                int c = in[offset + count++];
                if (((b & 0xC0) != 0x80) || ((c & 0xC0) != 0x80)) {
                    throw new UTFDataFormatException("bad second or third byte at " + (count - 2));
                }
                out[s++] = (char) (((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F));
            } else {
                throw new UTFDataFormatException("bad byte at " + (count - 1));
            }
        }
        return new String(out, 0, s);
    }

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

此错误表示文件已损坏(即:未正确编码UTF8)。你在写完文件后正确关闭文件吗?我可以想象,如果您正在写入缓冲的输出流并且未正确关闭流,则会出现这些错误。然后,一些字节将不会被写入,并且您将有一个无法重新读取的损坏文件。

相关问题