DataInputStream 和 DataOutputStream 数据流


DataInputStream 和 DataOutputStream 数据流


 /*
    3. 数据流
    3.1 DataInputStream 和 DataOutputStream
    3.2 作用:用于读取或写出基本数据类型的变量或字符串

    练习: 将内存中的字符串,基本数据类型的变量写出到文件中

    注意: 处理异常的话,仍然应该使用try-catch-finally
     */
    @Test
    public void test3() throws IOException {
        //1
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));

        //2
        dos.writeUTF("梁启晨");
        dos.flush();   // 刷新操作,将内存中的数据写入文件
        dos.writeInt(23);
        dos.flush();
        dos.writeBoolean(true);
        dos.flush();

        //3
        dos.close();
    }
    /*
    将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。

    注意点:读取不同类型数据的顺序,要与当初写入文件时,保存的数据类型一致
     */
    @Test
    public void test4() throws IOException {
        //1.
        DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
        //2.
        String name = dis.readUTF();
        int age = dis.readInt();
        boolean isMale = dis.readBoolean();

        System.out.println("name" + name);
        System.out.println("age" + age);
        System.out.println("isMale" + isMale);
        //3.
        dis.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值