Java 8: Copy directory recursively?

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

    This version uses Files.walk and Path parameters as Java 8 suggests.

    public static void copyFolder(Path src, Path dest) {
        try {
            Files.walk( src ).forEach( s -> {
                try {
                    Path d = dest.resolve( src.relativize(s) );
                    if( Files.isDirectory( s ) ) {
                        if( !Files.exists( d ) )
                            Files.createDirectory( d );
                        return;
                    }
                    Files.copy( s, d );// use flag to override existing
                } catch( Exception e ) {
                    e.printStackTrace();
                }
            });
        } catch( Exception ex ) {
            ex.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2021-02-03 20:08

    Using Files.walkFileTree:

    • you don't need to worry about closing Streams.
      (some other answers here forget that while using Files.walk)
    • handles IOException elegantly.
      (Some other answers here would become more difficult when adding proper exception handling instead of a simple printStackTrace)
        public void copyFolder(Path source, Path target, CopyOption... options)
                throws IOException {
            Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
    
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    createDirectories(target.resolve(source.relativize(dir)));
                    return FileVisitResult.CONTINUE;
                }
    
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                        throws IOException {
                    copy(file, target.resolve(source.relativize(file)), options);
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    

    What this does is

    • walk recursively over all files in the directory.
    • When a directory is encountered (preVisitDirectory):
      create the corresponding one in the target directory.
    • When a regular file is encountered (visitFile):
      copy it.

    options can be used to tailor the copy to your needs. For example to overwrite existing files in the target directory, use copyFolder(source, target, StandardCopyOption.REPLACE_EXISTING);

    0 讨论(0)
  • 2021-02-03 20:09

    In this way the code looks a bit simpler

    import static java.nio.file.StandardCopyOption.*;
    
    public  void copyFolder(Path src, Path dest) throws IOException {
        try (Stream<Path> stream = Files.walk(src)) {
            stream.forEach(source -> copy(source, dest.resolve(src.relativize(source))));
        }
    }
    
    private void copy(Path source, Path dest) {
        try {
            Files.copy(source, dest, REPLACE_EXISTING);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    
    0 讨论(0)
  • 2021-02-03 20:14

    How about the following code

    public void copyFolder(File src, File dest) throws IOException {
            try (Stream<Path> stream = Files.walk(src.toPath())) {
                stream.forEachOrdered(sourcePath -> {
    
                    try {
                        Files.copy(
                                /*Source Path*/
                                sourcePath,
                                /*Destination Path */
                                src.toPath().resolve(dest.toPath().relativize(sourcePath)));
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                });
            }
        }
    
    0 讨论(0)
  • 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<Path>() {
                @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.

    0 讨论(0)
  • 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();
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题