为了账号安全,请及时绑定邮箱和手机立即绑定

Java的DataInputStream的readUTF方法是怎么读取字符串的???

Java的DataInputStream的readUTF方法是怎么读取字符串的???

皈依舞 2019-03-19 17:19:26
大神们好,我是新手小白,今天在学习Java的IO操作中遇到一个百思不得其解的问题,下面的代码是今天做的关于DataInputStream类的练习,我很不解为什么DataInputStream的readUTF方法不需要任何参数,但是却在读取的时候可以知道自己读取多长,不明白他是怎么知道我当初在写入的时候写入的长度的,他是靠什么控制读取的范围的呀???比如下面的程序,readUTF方法就可以知道读取"昨天"这两个字,是怎么知道我就刚好需要读这两个字,而不会把下面的内容给读出。很是感谢大家的回答package com.zhang.hello;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class IODataStreamTest {    public static void main(String[] args) throws IOException {        File file=new File("f:/zhang.dat");        if(!file.exists()){            file.createNewFile();        }        DataInputStream dis=new DataInputStream(new FileInputStream(file));        DataOutputStream dos=new DataOutputStream(new FileOutputStream(file));        int testInt=2016;        double testDouble=10.12;        long testLong=20161012;        dos.writeInt(testInt);        dos.writeDouble(testDouble);        dos.writeLong(testLong);        //utf-8 一个中文占3个字节        dos.writeUTF("昨天");        dos.writeUTF("今天是个好日子");        dos.close();                int testRInt=dis.readInt();        System.out.println(testRInt);        double testRDouble=dis.readDouble();        System.out.println(testRDouble);        long testRLong=dis.readLong();        System.out.println(testRLong);        String testRStr=dis.readUTF();//为什么readUTF知道读取多长        System.out.println(testRStr);        dis.close();    }}执行结果:201610.1220161012昨天
查看完整描述

2 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

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

Reads two input bytes and returns an int value in the range 0 through

  1. Let a be the first byte read and b be the second byte. The value returned is:

(((a & 0xff) << 8) | (b & 0xff)) This method is suitable for reading
the bytes written by the writeShort method of interface DataOutput if
the argument to writeShort was intended to be a value in the range 0
through 65535. Returns: the unsigned 16-bit value read. Throws:
EOFException - if this stream reaches the end before reading all the

  1. IOException - if an I/O error occurs.

readUTF的Doc:

Reads from the stream in a representation of a Unicode character
string encoded in modified UTF-8 format; this string of characters is
then returned as a String. The details of the modified UTF-8
representation are exactly the same as for the readUTF method of
DataInput.


查看完整回答
反对 回复 2019-04-25
  • 2 回答
  • 0 关注
  • 887 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号