用IO实现文件拷贝

分析:
要想实现数据的拷⻉肯定是要通过流的⽅式来完成,对于流有两类,由于要拷⻉的内容不⼀定是⽂字数据,所以次此处我们采⽤字节流。
在进⾏⽹络数据传输、磁盘数据都是以字节形式保存数据的。
步骤:
1.将路径变为文件(String path->file)
2.进行检验,源文件必须存在,即srcFile必须存在;目标文件目录必须存在,即dest目录必须存在
3.文件的读取和写入。(字节流的输入输出流)
代码实现:

 public static  void copyFile(String srcFilePath,String destFilePath) throws FileNotFoundException {
        //1.String path->file,把路径变为file
        if(srcFilePath==null||srcFilePath.isEmpty()){
            throw new IllegalArgumentException("srcFile must be not null");
        }
        File scrFile=new File(srcFilePath);
         File destFile=new File(destFilePath);
        //2.检验工作: srcFile必须存在;dest目录必须存在,不存在创建
        if(!scrFile.isFile()||!scrFile.exists()){
            throw new IllegalArgumentException(scrFile+"is not File or exists");
        }

        File parent=destFile.getParentFile();
        if(!parent.exists()){
            parent.mkdirs();   //若父目录不存在,创造
        }
        //3.文件读取和写入
        try(InputStream in=new FileInputStream(scrFile); OutputStream out=new FileOutputStream(destFile)){
            byte[] buff=new byte[1024*1024]; 
            int len=-1;
            while((len=in.read(buff))!=-1){
                out.write(buff,0,len);
            }
               out.flush();
        } catch(FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_42373873/article/details/90577687