io - Java的DataInputStream的readUTF方法是怎么读取字符串的???
大家讲道理
大家讲道理 2017-04-18 10:08:37
0
2
442
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(2)
左手右手慢动作

DataOutputStream

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");

    byte[] bytearr = null;
    if (out instanceof DataOutputStream) {
        DataOutputStream dos = (DataOutputStream)out;
        if(dos.bytearr == null || (dos.bytearr.length < (utflen+2)))
            dos.bytearr = new byte[(utflen*2) + 2];
        bytearr = dos.bytearr;
    } else {
        bytearr = new byte[utflen+2];
    }

    // 将字符串的字节长度写入流中
    bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF);
    bytearr[count++] = (byte) ((utflen >>> 0) & 0xFF);

    int i=0;
    for (i=0; i<strlen; i++) {
       c = str.charAt(i);
       if (!((c >= 0x0001) && (c <= 0x007F))) break;
       bytearr[count++] = (byte) c;
    }

    for (;i < strlen; i++){
        c = str.charAt(i);
        if ((c >= 0x0001) && (c <= 0x007F)) {
            bytearr[count++] = (byte) c;

        } else if (c > 0x07FF) {
            bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
            bytearr[count++] = (byte) (0x80 | ((c >>  6) & 0x3F));
            bytearr[count++] = (byte) (0x80 | ((c >>  0) & 0x3F));
        } else {
            bytearr[count++] = (byte) (0xC0 | ((c >>  6) & 0x1F));
            bytearr[count++] = (byte) (0x80 | ((c >>  0) & 0x3F));
        }
    }
    out.write(bytearr, 0, utflen+2);
    // 写入的长度在字符串中增加了2,即字节长度标识所占用的资源
    return utflen + 2;
}

DataInputStream

public final static String readUTF(DataInput in) throws IOException {
    // 读取字符串字节长度
    int utflen = in.readUnsignedShort();
    //...
}

实际上在调用writeUTF写入时jdk内部有将字符串的字节数写入流中,读取时先读取到字节长度,按照指定的字节长度读取出相应的字符串。

左手右手慢动作

看源码,调用的第一句话就获得了长度
int utflen = in.readUnsignedShort();
这个方法的文档:

读取两个输入字节并返回 0 到范围内的 int 值

  1. 设a为读取的第一个字节,b为第二个字节。返回的值为:

(((a & 0xff) DataOutput 接口的 writeShort 方法写入的字节 if
the writeShort 的参数旨在成为 0
through 65535 范围内的值。返回:读取的无符号 16 位值。抛出:
EOFException - 如果该流在读取所有

之前到达末尾
  1. IOException - 如果发生 I/O 错误。

readUTF的文档:

以 Unicode 字符的表示形式从流中读取
修改后的 UTF-8 格式编码的字符串;这串字符
然后以 String 的形式返回。修改后的UTF-8
表示的细节与
DataInput.

的readUTF方法完全相同
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板