首页 > 其他分享 >IO3 - buffer

IO3 - buffer

时间:2023-01-04 14:44:20浏览次数:30  
标签:buffIn buffer data IO3 new null TODO buffOut

buffer

public class FileCopy_Buffer {
    public static void main(String[] args) throws Exception{

        //TODO IO 文件复制

        //数据源文件对象
        File srcFile = new File("E:\\.就业\\code\\day1\\IO_File\\test.txt");

        //数据目的文件对象(自动生成)
        File destfile = new File("E:\\.就业\\code\\day1\\IO_File\\test.txt.copy");

        //TODO FileInputStream  文件输入流(管道对象)
        FileInputStream in = null;
        //TODO FileOutputStream  文件输出流(管道对象)
        FileOutputStream out = null;

        //TODO BufferedInputStream  缓冲输入流(管道对象)
        BufferedInputStream buffIn = null;
        //TODO BufferedOutputStream  缓冲输出流(管道对象)
        BufferedOutputStream buffOut = null;

        //TODO 创建缓冲区
        byte[] cache = new byte[2];

        try{
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destfile);

            buffIn = new BufferedInputStream(in);    //与文件输出管道对接
            buffOut = new BufferedOutputStream(out); //与文件输入管道对接
            //阀门开关用 buffIn和buffOut 操作

            //每一打开阀门只传输一个数据
            //TODO .read()  打开阀门,流转数据(输入数据到管道)
            //int data = in.read();
            //TODO .write(data)  打开阀门,流转数据(从管道输出数据)
            //out.write(data);
            //如果文件数据全部读取后,再读取,则读取结果为 -1 (表示无效-结尾)

            int data = -1;
            while ((data = buffIn.read(cache)) != -1){
                //每一次将文件数据尽可能多的放入缓冲区 -- 最大为 buffer容量cache
                buffOut.write(cache,0, data);
                //缓冲区数据量为 0 时停止 -- 每一次将缓冲区中所有数据输出
            }

        }catch (IOException e){
            throw new RuntimeException(e);
        }finally {
            //TODO 关闭管道
            if(buffIn != null){
                try {
                    buffIn.close();
                }catch (IOException e){
                    throw new RuntimeException(e);
                }
            }
            if(buffOut != null){
                try {
                    buffOut.close();
                }catch (IOException e){
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

标签:buffIn,buffer,data,IO3,new,null,TODO,buffOut
From: https://www.cnblogs.com/Ashen-/p/17024782.html

相关文章