Java 8: Copy directory recursively?

后端 未结 6 1652
伪装坚强ぢ
伪装坚强ぢ 2021-02-03 19:47

I see that Java 8 has significantly cleaned up reading the contents of a file into a String:

String contents = new String(Files.readAllBytes(Paths.get(new URI(so         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-03 20:18

    my version:

    static private void copyFolder(File src, File dest) {
        // checks
        if(src==null || dest==null)
            return;
        if(!src.isDirectory())
            return;
        if(dest.exists()){
            if(!dest.isDirectory()){
                //System.out.println("destination not a folder " + dest);
                return;
            }
        } else {
            dest.mkdir();
        }
    
        File[] files = src.listFiles();
        if(files==null || files.length==0)
            return;
    
        for(File file: files){
            File fileDest = new File(dest, file.getName());
            //System.out.println(fileDest.getAbsolutePath());
            if(file.isDirectory()){
                copyFolder(file, fileDest);
            }else{
                if(fileDest.exists())
                    continue;
    
                try {
                    Files.copy(file.toPath(), fileDest.toPath());
                } catch (IOException e) {
                    //e.printStackTrace();
                }
            }
        }
    }
    

提交回复
热议问题