DataInputStream和DataOutputStream

Posted woqiaoxun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DataInputStream和DataOutputStream相关的知识,希望对你有一定的参考价值。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataStream {
    public static void main(String[] args) throws IOException {
//        write("test5.txt");
//        read("test5.txt");
        readFromBuffer(writeToBuffer());
    }
    
    //write to local file
    public static void write(String path) throws IOException{
        DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
        out.writeInt(1);
        out.writeShort(2);
        out.writeLong(1);
        out.writeUTF("Some text");
        out.flush();
        out.close();
    }
    
    //read from local file
    public static void read(String path) throws IOException{
        DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(path)));
        
        System.out.println(in.readInt());
        System.out.println(in.readShort());
        System.out.println(in.readLong());
        System.out.println(in.readUTF());
        in.close();
    }
    
    //write to byte array
    public static byte[] writeToBuffer() throws IOException{
        byte[] buff = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(new BufferedOutputStream(bos));
        out.writeInt(1);
        out.writeShort(2);
        out.writeLong(1);
        out.writeUTF("Some text");
        out.flush();
        out.close();
        buff = bos.toByteArray();
        bos.close();
        return buff;
    }
    
    //read from byte array
    public static void readFromBuffer(byte[] b) throws IOException{
        DataInputStream in = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(b)));
        
        System.out.println(in.readInt());
        System.out.println(in.readShort());
        System.out.println(in.readLong());
        System.out.println(in.readUTF());
        in.close();
    }
    
}

 

以上是关于DataInputStream和DataOutputStream的主要内容,如果未能解决你的问题,请参考以下文章

JAVA IO操作:数据操作流:DataOutputStream和DataInputStream

数据流: DataInputStream 和 DataOutputStream

DataInputStream和DataOutputStream

DataOutputStream和DataInputStream

JavaI/O:简单的使用DataOutputStream和DataInputStream操作文件流

大数据必学Java基础(七十三):数据流DataInputStream和DataOutputStream介绍