当前位置:网站首页>NiO file and folder operation examples

NiO file and folder operation examples

2022-06-22 16:28:00 The force is with you

Count the number of specific files in a folder

public static void main(String[] args) throws IOException {
    
		//  Count the number of folders 
        AtomicInteger dirCount = new AtomicInteger();
        //  Count the number of file occurrences 
        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);
    }

Output :

dir count: 136
file count: 724

Delete files and folders

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);
            }
        });
    }

Multi level file replication

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();
                }
            }
        });
    }
原网站

版权声明
本文为[The force is with you]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221508060492.html