IO_数据流

处理八大数据类型,包括字符串
保留数据的同时也保留了数据类型,方便后期获取数据类型而不需要强转
记住:
1、先写出(目的是获得数据类型)再读取
2、读取顺序和写出顺序保持一致

程序 -(写入)-> DataOutputStream(i.e OutputStream(i.e FileOutputStream) )-(写入)-> 文件
程序 -(读取)-> DataInputStream(i.e InputStream(i.e FileInputStream) ) <-(读取)- 文件

在这里插入图片描述

方法描述
DataInputStream(InputStream in)使用指定的底层 InputStream 创建一个 DataInputStream
DataOutputStream(OutputStream out)创建一个新的数据输出流,将数据写入指定基础输出流
writeUTF(String str)以与机器无关方式使用 UTF-8 修改版编码将一个字符串写入基础输出流

测试代码:

public class DataTest {
	public static void main(String[] args) throws IOException {
//		①写出
//		因为要获取ByteArrayOutputStream的toByteArray的内容,所以要设变量baos
		ByteArrayOutputStream baos = new ByteArrayOutputStream();/*不用释放*/
		DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(baos));/*写到字节数组*/
//		操作数据类型+数据(数据写到ByteArrayOutputStream再到datas)
		dos.writeUTF("编码辛酸泪");/*1.字符串*/
		dos.writeInt(18);/*2.数字*/
		dos.writeBoolean(true);/*3.布尔值*/
		dos.writeChar('A');/*4.字符*/
		dos.flush();
		byte[] datas = baos.toByteArray();/*任何数据都可以转成字节数组*/
		System.out.println(datas.length);/*24*/
//		②读取
		DataInputStream dis = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
//		读取顺序与写出一致(如果顺序出错:Exception in thread "main" java.io.EOFException)
		String str = dis.readUTF();/*1.字符串*/
		int age = dis.readInt();/*2.数字*/
		boolean flag = dis.readBoolean();/*3.布尔值*/
		char a = dis.readChar();/*4.字符*/
		System.out.println(flag);
	}
}

运行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值