Java 8: Copy directory recursively?

后端 未结 6 1651
伪装坚强ぢ
伪装坚强ぢ 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:15

    and one more version:

    static 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();
        }
    
        if(src.listFiles()==null || src.listFiles().length==0)
            return;
    
        String strAbsPathSrc = src.getAbsolutePath();
        String strAbsPathDest = dest.getAbsolutePath();
    
        try {
            Files.walkFileTree(src.toPath(), new SimpleFileVisitor() {
                @Override
                public FileVisitResult visitFile(Path file,
                        BasicFileAttributes attrs) throws IOException {
                    File dstFile = new File(strAbsPathDest + file.toAbsolutePath().toString().substring(strAbsPathSrc.length()));
                    if(dstFile.exists())
                        return FileVisitResult.CONTINUE;
    
                    if(!dstFile.getParentFile().exists())
                        dstFile.getParentFile().mkdirs();
    
                    //System.out.println(file + " " + dstFile.getAbsolutePath());
                    Files.copy(file, dstFile.toPath());
    
                    return FileVisitResult.CONTINUE;
                }
            });
    
        } catch (IOException e) {
            //e.printStackTrace();
            return;
        }
    
        return;
    }
    

    its code use java8 Files.walkFileTree function.

提交回复
热议问题