节点流输入输出流

 节点流

字节数组输入流:ByteArrayInputStream      read(byte[] b,int off,int len)+close()

                输出流:ByteArrayOutputStream     write(byte[] b,int off,int len)+toByteArray()  新增方法不要使用多态

import java.io.*;

public class Demo06 {
    public static void main(String[] args) throws IOException {
        reader(write());
    }
    public static byte[] write() throws IOException {
        //目的地
        byte[] dest;
        //选择流 不同点
        ByteArrayOutputStream bos=new ByteArrayOutputStream();//不使用多态
        String string="爱我大中国";
        byte[] data=string.getBytes();
        //写入数据
        bos.write(data,0,data.length);
        dest=bos.toByteArray();
        bos.flush();
        bos.close();
        return dest;

    }
    public static void reader(byte[] data) throws IOException {
        //输入流
        InputStream is=new BufferedInputStream(new ByteArrayInputStream(data));
        byte[] flush=new byte[1024];
        int len=0;
        while(-1!=(len=is.read(flush))){
            System.out.println(new String(flush,0,len));
        }

        is.close();
    }
}

字节数组流和文件流对接

import java.io.*;

/**
 * 文件输入流->程序->字节数组流
 * 字节数组流->程序->文件输出流
 */
public class Demo07 {
    public static void main(String[] args) throws IOException {
        byte[] b=getByteArrayStream("D:/test.txt");
        for(int i=0;i<100;i++){
            toFileFromByteArray(b,"D:test2.txt");
        }

    }
    public static byte[] getByteArrayStream(String srcPath) throws IOException {
        //文件源
        File src=new File(srcPath);
        //目的地
        byte[] dest=null;
        //文件输入流
        InputStream is=new BufferedInputStream(new FileInputStream(src));
        //字节数组输出流不能使用多态
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        //不断读取文件 写出到字节数组流中
        byte[] flush=new byte[1024];
        int len=0;
        while(-1!=(len=is.read(flush))){
            //写出到字节数组流中
            bos.write(flush,0,len);
        }
        bos.flush();
        dest=bos.toByteArray();
        bos.close();
        is.close();
        return dest;
    }
    public static void toFileFromByteArray(byte[] src1,String destPath) throws IOException {
        //创建源
        //目的地
        File dest=new File(destPath);
        //字节数组输入流可以使用多态
        InputStream is=new BufferedInputStream(new ByteArrayInputStream(src1));
        OutputStream os=new BufferedOutputStream(new  FileOutputStream(dest,true));
        //不断读取
        byte[] flush=new byte[1024];
        int len=0;
        while(-1!=(len=is.read(flush))){
            os.write(flush,0,len);
        }
        os.flush();
        is.close();
        os.close();

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值