Java 8: Copy directory recursively?

后端 未结 6 1647
伪装坚强ぢ
伪装坚强ぢ 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();
        }
    }
    

提交回复
热议问题