首页 > 其他 > 详细

基于NIO2的遍历文件夹简单复制

时间:2019-09-27 10:25:54      阅读:121      评论:0      收藏:0      [点我收藏+]
    public Class CopyAndWrite {

        public static final String SOURCES = "D:\\sources";
        public static final String TARGET = "D:\\target";

        public static void main (String[]args) throws IOException {

            Path startingDir = Paths.get(SOURCES);
    
            Files.walkFileTree(startingDir, new FindJavaVisitor());
        }

        private static class FindJavaVisitor extends SimpleFileVisitor<Path> {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (!StringUtils.equals(dir.toString(), SOURCES)) {
                    Path targetPath = Paths.get(TARGET + dir.toString().substring(SOURCES.length()));
                    if (!Files.exists(targetPath)) {
                        Files.createDirectory(targetPath);
                    }
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path targetPath = Paths.get(TARGET + file.toString().substring(SOURCES.length()));
                copyFile(targetPath, Files.readAllBytes(file));

                return FileVisitResult.CONTINUE;
            }
        }

        private static void copyFile (Path path,byte[] bytes){
            // write file
            try {
                Files.write(path, bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

基于NIO2的遍历文件夹简单复制

原文:https://www.cnblogs.com/Deters/p/11595624.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!