码迷,mamicode.com
首页 > 其他好文 > 详细

DataInputStream和DataOutputStream

时间:2016-10-27 23:18:45      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:fileinput   throw   except   imp   stream   str   output   rom   java   

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

标签:fileinput   throw   except   imp   stream   str   output   rom   java   

原文地址:http://www.cnblogs.com/Iqiaoxun/p/6005739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!