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();
    }
    
}

 

posted on 2016-10-27 21:46  woqiaoxun  阅读(293)  评论(0编辑  收藏  举报