Java的DataInputStream的readUTF方法是怎么读取字符串的??? 财富值11

2016-10-12 11:33发布

大神们好,我是新手小白,今天在学习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();     } } 

执行结果:
2016
10.12
20161012
昨天

友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
该问题目前已经被作者或者管理员关闭, 无法添加新回复
10条回答

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

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

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

DataInputStream

(((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

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.

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

IOException - if an I/O error occurs.

readUTF的Doc:

DataOutputStream

一周热门 更多>