Java------IO流之数据流

数据流

DataInputStream与DataOutputStream

  • DataOutputStream : 数据专属流

    • 这个流可以将数据连同数据的类型一并写入文件

      注意!:这个文件不是普通文本文件(这个文件使用记事本打不开)

  • DataInputStream : 数据字节输入流

    • DataOutputStream写的文件,只能使用DataInputStream去读,并且读的时候需要提前写入的顺序
    • 读的顺序需要和写入的顺序一致,才能正常取出数据

代码示例

public class DataOutputStreamTest {
    public static void main(String[] args) {

        DataOutputStream bos = null ;
        DataInputStream in = null ;

        try {
            bos = new DataOutputStream(new FileOutputStream("data"));
            in = new DataInputStream(new FileInputStream("data"));

            //写数据
            byte a = 100 ;
            short b = 200 ;
            int c = 300 ;
            long d = 400L ;
            float e = 3.0F ;
            double f =3.14 ;
            boolean g = false ;
            char h = 'a' ;

            //写
            bos.writeByte(a);
            bos.writeShort(b);
            bos.writeInt(c);
            bos.writeLong(d);
            bos.writeFloat(e);
            bos.writeDouble(f);
            bos.writeBoolean(g);
            bos.writeChar(h);

            //开始读
            byte q =in.readByte();
            short w = in.readShort();
            int r = in.readInt();
            long t = in.readLong();
            float y = in.readFloat();
            double u = in.readDouble();
            boolean i = in.readBoolean();
            char o = in.readChar();

            System.out.println(q);
            System.out.println(w);
            System.out.println(r+1000);
            System.out.println(t);
            System.out.println(y);
            System.out.println(u);
            System.out.println(i);
            System.out.println(o);



            bos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos!=null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in!=null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

运行结果:

100
200
1300
400
3.0
3.14
false
a
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值