ByteArrayOutputStream/ByteArrayInputStream

本文详细介绍了Java中ByteArrayOutputStream和ByteArrayInputStream的基本使用方法,包括如何将整型数据转换为字节数组,如何从文件中读取数据到ByteArrayOutputStream并输出,以及如何将BufferedImage对象输出到OutputStream。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.基础介绍

ByteArrayOutputStream:   可以捕获内存缓冲区的数据,转换成字节数组 /字符串

ByteArrayInputStream: 可以将字节数组转化为输入流

public static void main(String[] args) {
		
		int a = 222;   
	    int b = 1;   
	    int c = 2;   
	    ByteArrayOutputStream bout = new ByteArrayOutputStream();   
	    //bout的write()每次都只能写入int类型的数据
	    bout.write(a);   
	    bout.write(b);   
	    bout.write(c);   
	    //将bout中缓存的数据转化为byte[]
	    byte[] buff = bout.toByteArray();   
	    for (int i = 0; i < buff.length; i++)   
	        System.out.println(buff[i]);   
	    System.out.println("***********************");   
	    
	    //新建bais是必须用byte[]初始化
	    ByteArrayInputStream bin = new ByteArrayInputStream(buff);   
	    //read[]每次返回一个字节.若无返回-1
	    while ((b = bin.read()) != -1) {   
	        System.out.println(b);   
	    }   

		
	}

二.将文件中的数据保存到ByteArrayOutputStream并输出

public static void main(String[] args) {
		
		try {
			//file的相对路径在其项目路径下开始
			FileInputStream in=new FileInputStream("a.txt");
			
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			byte[] by=new byte[4];   //即数据充足的情况下,每次读4个字节
			int length=0;
			//read()方法读到规定好的字节数组中,并返回读取的字节长度
			try {
				while(-1!=(length=in.read(by))){
					System.out.println(length);
			//将字节数组写入到baos		
					baos.write(by,0,length);
					String s=baos.toString();
					System.out.println(s);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

三.将图片输出

BufferedImage-->ByteArrayOutputStream---->字节数组----->OutputStream输出

public static void output(BufferedImage image,OutputStream out) {
		ByteArrayOutputStream byteout=new ByteArrayOutputStream();
		try {
			
			ImageIO.write(image, "JPEG", byteout);
			byte[] buffer=byteout.toByteArray();
			out.write(buffer);
			byteout.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值