Implementation file copy with IO

Analysis:
To achieve copy ⻉ data will definitely have to be done by the stream shutter mode, there are two categories for flow, due to the content ⻉ copy of the file is not ⼀ given word data, so times where we recorded using a byte stream .
Open networks data transmission, disk data is stored in the form of data bytes into ⾏.
Steps:
1. path changed file (String path-> File)
2. inspection, the source file must exist, namely srcFile must exist; the target directory must exist, namely dest directory must exist
to read and write files 3. into. (Input and output flow stream of bytes)
code for:

 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();
        }
    }

Guess you like

Origin blog.csdn.net/weixin_42373873/article/details/90577687