JavaIO-字节数组流(ByteArrayOutputStream)

一)ByteArrayOutputStream介绍

概述:该类实现了将数据写入字节数组的输出流。 当数据写入缓冲区时,缓冲区会自动增长。 数据可以使用toByteArray()和toString() 。

 

初始化构造方法:

1、ByteArrayOutputStream()

创建一个新的字节数组输出流。 默认的大小为32。

2、ByteArrayOutputStream(int size)

创建一个新的字节数组输出流,具有指定大小的缓冲区容量(以字节为单位)。

 

二)ByteArrayOutputStream场景详解

场景一:默认构造方法

/**
 * 场景一
 */
public static void method1() {
    InputStream in = null;
    ByteArrayOutputStream out = null;
    try {
        in = new FileInputStream(new File("D:\\io\\a.txt"));

        out = new ByteArrayOutputStream();
			
        byte[] bytes = new byte[1024*8];
			
        int len = 0;
        while((len = in.read(bytes)) != -1){
            out.write(bytes, 0, len);
        }
	        
        System.out.println(out.toString("GBK"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

场景二:指定大小数组构造方法

/**
 * 场景二
 */
public static void method2() {

    InputStream in = null;
    ByteArrayOutputStream out = null;
    try {
        in = new FileInputStream(new File("D:\\io\\a.txt"));

        out = new ByteArrayOutputStream(32);
			
        int len = 0;
        while((len = in.read()) != -1){
            out.write(len);
        }
        System.out.println(out.toString("GBK"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

识别二维码关注个人微信公众号

本章完结,待续,欢迎转载!
 
本文说明:该文章属于原创,如需转载,请标明文章转载来源!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值