IO2 - 文件复制

文件复制

基本的文件流传输

  • 问题:效率不高,每次只能传输一个数据,大量数据传输时需要反复开关阀门
public class FileCopy {
    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;

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

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

            int data = -1;
            while ((data = in.read()) != -1){
                out.write(data);
            }

        }catch (IOException e){
            throw new RuntimeException(e);
        }finally {
            //TODO 关闭管道
            if(in != null){
                try {
                    in.close();
                }catch (IOException e){
                    throw new RuntimeException(e);
                }
            }
            if(out != null){
                try {
                    out.close();
                }catch (IOException e){
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
posted @   LaViez  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
点击右上角即可分享
微信分享提示