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

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

昨天


皈依舞
浏览 888回答 2
2回答

慕码人8056858

看源码,调用的第一句就获取了长度int utflen = in.readUnsignedShort();这个方法的Doc :Reads two input bytes and returns an int value in the range 0 throughLet 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 readingthe bytes written by the writeShort method of interface DataOutput ifthe argument to writeShort was intended to be a value in the range 0through 65535. Returns: the unsigned 16-bit value read. Throws:EOFException - if this stream reaches the end before reading all theIOException - if an I/O error occurs.readUTF的Doc:Reads from the stream in a representation of a Unicode characterstring encoded in&nbsp;modified UTF-8 format; this string of characters isthen returned as a String. The details of the modified UTF-8representation are exactly the same as for the readUTF method ofDataInput.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java