Java 字节数组流

字节数组流,即向内存数组读/取数据,实现数据在流与流之间的传递。

与字节流别无二致。

  • ByteInputStream:

package SAMPLE.IO流;
import java.io.*;
/*文件 字节数组输入流
   1、确定源:字节数组,不要太大
   2、选择流 文件输入流:ByteArrayInputStream
   3、操作 (没有“文件不存在”异常)
   4、释放资源,可以不处理
 */
public class ByteArrayIn字节数组流 {
    public static void main(String[] args) {
        //创建源
        byte[] src = "talk is cheap, show me the code".getBytes();
        //选择流
        ByteArrayInputStream bais = null;//扩展作用域
        try {
            bais = new ByteArrayInputStream(src);
            //操作(分段读取)
            byte[] flush = new byte[5];//缓存容器,字节流为字节数组。
            int len = -1;//接收长度
            while((len=bais.read(flush))!=-1){
                //字节数组-->字符串(解码)
                String str = new String(flush,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取失败");
        }finally {
            //此处close为空方法,字节数组会通过垃圾回收机制刷新
            try {
                if(bais!=null)
                    bais.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("关闭输入流失败");
            }
        }
    }
}

小结:

1、字节数组流不涉及对系统文件的操作,而是在内存中进行维护。

2、基于垃圾回收机制释放资源,close()变得没有必要。

  • ByteOutputStream:

package SAMPLE.IO流;
import java.io.*;
/*文件 字节数组输出流
   1、确定源(内部维护)
   2、选择流 不关联源
   3、操作
   4、释放资源 可以不用
 */
public class ByteArrayOut字节数组流 {
    public static void main(String[] args) {
        //创建源
        byte[] dest = null;
        //选择流
        ByteArrayOutputStream baos = null;//扩展作用域
        try {
            baos = new ByteArrayOutputStream();//不关联源,无源内数据入流,而是流内数据入源
            //操作(写出)
            String msg = "show me the code";
            byte[] datas = msg.getBytes();//字符串-->字节数组(编码)
            baos.write(datas,0,datas.length);//追加形式
            baos.flush();
            //获取数据
            dest = baos.toByteArray();
            System.out.println(new String(dest,0,dest.length));

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("写出失败");
        }finally {
            //释放资源close,在此处可有可无
            try {
                if(baos!=null)
                    baos.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("关闭输出流失败");
            }
        }
    }
}

小结:

1、不关联系统文件,写出的数据在内存中维护。

2、close()不必要。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值