writeUTF輸出字符串失敗的原因分析

字號:

字符串比較長了之后,數(shù)據(jù)就發(fā)不過去了,經(jīng)檢查JDK的源代碼,原來有長度限制。為了保險起見,我們還是不要超過65535/3 ,取20000好了。
    public final void writeUTF(String str) throws IOException {
    writeUTF(str, this);
    }
    static int writeUTF(String str, DataOutput out) throws IOException {
    int strlen = str.length();
    int utflen = 0;
    int c, count = 0;
    /* use charAt instead of copying String to char array */
    for (int i = 0; i < strlen; i++) {
    c = str.charAt(i);
    if ((c >= 0x0001) && (c <= 0x007F)) {
    utflen++;
    } else if (c > 0x07FF) {
    utflen += 3;
    } else {
    utflen += 2;
    }
    }
    if (utflen > 65535)
    throw new UTFDataFormatException("encoded string too long: " + utflen + " bytes");
    // 其他的語句
    }