java.io.datainputstream.readunsignedshort_Java的DataInputStream的readUTF方法是怎么读取字符串的???...

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

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内部有将字符串的字节数写入流中,读取时先读取到字节长度,按照指定的字节长度读取出相应的字符串。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值