Java文件复制

主要是工作代码,无解释。

    /**
     * 将文件或文件夹source复制到dest
     * <br>目标文件检测:
     * <br> a.当文件不存在时:需要创建文件
     * <br>  根据是否有后缀名来确定是创建的是文件夹还是文件,有后缀名时创建文件
     * <br>  如果创建的是文件夹则会将source复制到dest文件夹中。
     * <br>  如果是文件,则直接将source复制为dest
     * <br> b.当文件存在时:需要判断目标文件是文件夹还是文件
     * <br>  如果是文件夹,在该文件夹下创建以来源文件名命名的文件
     * @param source
     * @param dest 
     */
    public static void moveFile(File source,File dest) throws FileNotFoundException,IOException{
        FileInputStream fis = null;
        FileChannel fc= null;
        FileOutputStream fout= null;
        WritableByteChannel to= null;
        try {
            if(!source.exists()){
                System.out.println("源文件不存在!");
                return ;
            }
            if(source.isDirectory()){
                File[] srcs = source.listFiles();
                for(File src:srcs){
                    moveFile(src,new File(dest.getPath()+File.separator+src.getName()));
                }
            }else{
                if(!dest.exists()){
                    if(!new File(dest.getParent()).exists()){
                        new File(dest.getParent()).mkdirs();
                    }
                    //根据是否有后缀名来确定是创建的是文件夹还是文件,有后缀名时创建文件。
                    if(dest.getName().matches(".*\..*")){
                        dest.createNewFile();
                    }else{
                        dest.mkdir();
                        dest = new File(dest.getPath()+File.separator+source.getName());
                        dest.createNewFile();
                    }
                }else{
                    //当目标文件存在时,需要判断目标文件是文件夹还是文件,如果是文件夹,在该文件夹下创建以来源文件名命名的文件
                    if(!dest.getName().matches(".*\..*")){
                        dest = new File(dest.getPath()+File.separator+source.getName());
                        dest.createNewFile();
                    }
                }
                fis = new FileInputStream(source);
                fc=fis.getChannel(); 
                fout=new FileOutputStream(dest); 
                to=fout.getChannel(); 
                fc.transferTo(0,fc.size(),to); 
                fis.close();
                fc.close();
                fout.flush();
                fout.close();
                to.close();
            }
        } catch (FileNotFoundException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } finally {
            if(fis!=null){
                fis.close();
            }
            if(fc!=null){
                fc.close();
            }
            if(fout!=null){
                fout.flush();
                fout.close();
            }
            if(to!=null){
                to.close();
            }
        }
    }
原文地址:https://www.cnblogs.com/justbeginning/p/3914271.html