byte数组转blob类型_字节数组流详解

5a7b5ff79e12c8446f573a28965df192.png

ByteArrayInputStreamByteArrayOutputStream经常用在需要流和数组之间转化的情况!

说白了,FileInputStream是把文件当做数据源。ByteArrayInputStream则是把内存中的”某个字节数组对象”当做数据源。字节数组流只有字节流,没有字符流 ,属于节点流。

1、简单测试ByteArrayInputStream的使用:

public class TestByteArrayInputStream {
	public static void main(String[] args) {
		//将字符串转换成字节数组
		byte[] buf = "你好,java!".getBytes();
		read(buf);
	}
	public static void read(byte[] buf) {
		ByteArrayInputStream bais = null;
		try {
			//该构造方法的参数是一个字节数组
			bais = new ByteArrayInputStream(buf);
			StringBuilder sb = new StringBuilder();
			int temp = 0;
			int num = 0;//用于保存读取的字节数
			while((temp = bais.read()) != -1) {
				sb.append((char)temp);
				num++;
			}
			System.out.println(sb);
			System.out.println("读取的字节数:" + num);
		} finally {
			try {
				if(bais != null)
					bais.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

运行结果:

772b027d65757b41acf0858356773cba.png

2、测试ByteArrayInputStream/ByteArrayOutputStream的使用:

public class TestByteArrayStream {
	public static void main(String[] args) {
		byte[] buf = write();//写对象方法,返回值为byte类型数组
		read(buf);//读对象的方法
	}
	public static byte[] write() {
		//创建字节数组流对象
		ByteArrayOutputStream baos = null;
		ObjectOutputStream oos = null;
		try {
			//目的地是字节数组,底层默认创建一个长度为32的字节数组
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			//写出数据,将数据写入字节数组流中
			oos.writeInt(97);
			oos.writeDouble(3.14);
			oos.writeChar('a');
			oos.writeBoolean(true);
			oos.writeObject(new Date(1000));
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//关闭流
			try {
				if(oos != null)
					oos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return baos.toByteArray();
	}
	
	public static void read(byte[] buf) {
		//创建对象
		ByteArrayInputStream bais = null;
		ObjectInputStream ois = null;
		try {
			//数据源是byte类型的数组
			bais = new ByteArrayInputStream(buf);
			ois = new ObjectInputStream(bais);
			//读数据
			System.out.println(ois.readInt());
			System.out.println(ois.readDouble());
			System.out.println(ois.readChar());
			System.out.println(ois.readBoolean());
			System.out.println(ois.readObject());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//关闭流
			try {
				if(ois != null)
					ois.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

运行结果:

47fb5c513717c719453452d07e626c45.png

尚学堂百战程序员

百战程序员_IT6000集_影响6000万学习IT的中国人【官网】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值