数据流

数据流

/**
 * @description DataIOTest
 * @author 小邱
 * @version 0.0.1
 * @since 2021/9/9 14:33
 */

import java.io.*;

public class DataIOTest {
    /*
        为了方便地操作Java语言的基本数据类型和String的数据
        数据流有两个类:(用于读取和写出基本数据类型、String类的数据)(将内存中的变量写到磁盘中以防丢失)
            DataInputStream 和 DataOutputStream
            分别“套接”在 InputStream 和 OutputStream 子类的流上
        DataInputStream中的方法:
            boolean readBoolean()          byte readByte()
            char readChar()                float readFloat()
            double readDouble()            short readShort()
            long readLong()                int readInt()
            String readUTF()               void readFully(byte[] b)
        DataOutputStream中的方法:
            将上述的方法的read改为相应的write即可。
     */
    public static void main(String[] args) {
        //写的过程
        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(new FileOutputStream("F:\\Lean\\Text\\src\\main\\resources\\b.txt"));
            dos.writeBoolean(true);
            dos.flush();
            dos.writeInt(12);
            dos.flush();
            dos.writeUTF("12344567");
            dos.flush();
            dos.writeFloat(12.3f);
            dos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (dos != null) {
                    dos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //读的过程
        //读取不同类型的数据顺序要与写出的顺序一致
        DataInputStream dis = null;
        try {
            dis = new DataInputStream(new FileInputStream("F:\\Lean\\Text\\src\\main\\resources\\b.txt"));
            System.out.println(dis.readBoolean());
            System.out.println(dis.readInt());
            System.out.println(dis.readUTF());
            System.out.println(dis.readFloat());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dis != null) {
                    dis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值