当前位置:网站首页>nio文件和文件夹操作例子

nio文件和文件夹操作例子

2022-06-22 15:10:00 原力与你同在

统计一个文件夹下特定文件的数目

public static void main(String[] args) throws IOException {
    
		// 统计文件夹出现的数目
        AtomicInteger dirCount = new AtomicInteger();
        // 统计文件出现的数目
        AtomicInteger fileCount = new AtomicInteger();

        Files.walkFileTree(Paths.get("D:\\soft\\java\\jdk"),new SimpleFileVisitor<Path>(){
    
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
    
                dirCount.getAndIncrement();
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    
                String string = file.toString();
                if(string.endsWith(".jar")){
    
                    fileCount.getAndIncrement();
                }
                return super.visitFile(file, attrs);
            }
        });
        System.out.println("dir count: "+dirCount);
        System.out.println("file count: "+fileCount);
    }

输出:

dir count: 136
file count: 724

删除文件和文件夹

public static void main(String[] args) throws IOException {
    
        Files.walkFileTree(Paths.get("D:\\a"),new SimpleFileVisitor<Path>(){
    
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    
                Files.delete(file);
                return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
    
                Files.delete(dir);
                return super.postVisitDirectory(dir, exc);
            }
        });
    }

多级别文件复制

public static void main(String[] args) throws IOException {
    
        String source = "D:\\a";
        String target = "D:\\b";

        Files.walk(Paths.get(source)).forEach(path->{
    
            String targetName = path.toString().replace(source,target);
            if(Files.isDirectory(path)){
    
                try {
    
                    Files.createDirectory(Paths.get(targetName));
                } catch (IOException e) {
    
                    e.printStackTrace();
                }
            }

            else if(Files.isRegularFile(path)){
    
                try {
    
                    Files.copy(path,Paths.get(targetName));
                } catch (IOException e) {
    
                    e.printStackTrace();
                }
            }
        });
    }
原网站

版权声明
本文为[原力与你同在]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43978420/article/details/122859753