MENU

DataIO & ByteArrayIo

June 25, 2018 • Read: 258 • Java

  • DataInputStream和DataOutputStream分别继承自InputStream和OutputStream,它属于处理流,需要分别”套接“在InputStream和OutputStream类型的节点流上
  • DataInputStream和DataOutputStream提供了可以存取与机器无关的Java原始类型数据的方法
  • DataInputStream和DataOutputStream的构造方法为:

    • DataInputStream(InputStream in)
    • DataOutputStream(OutputStream out)
import java.io.*;

public class TestFileInputStream {

    public static void main(String[] args) {
        ByteArrayOutputStream baos = 
                new ByteArrayOutputStream();
        DataOutputStream dos = 
                new DataOutputStream(baos);
        try {
            dos.writeDouble(Math.random());
            dos.writeBoolean(true);
            ByteArrayInputStream bais = 
                    new ByteArrayInputStream(baos.toByteArray());
            System.out.println(bais.available());//bais中有多少字节
            DataInputStream dis = 
                    new DataInputStream(bais);
            System.out.println(dis.readDouble());//先写的先读
            System.out.println(dis.readBoolean());
            dos.close();
            dis.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}

下面给一张图,帮助理解

最后编辑于: October 19, 2018
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment