(nio) Files Detailed related operations and demonstration codes, such as deleting, copying (multi-level) file directories, etc.

Files

Check if the file exists

Path path = Paths.get("helloword/data.txt");
System.out.println(Files.exists(path));

Create a first-level directory

Path path = Paths.get("helloword/d1");
Files.createDirectory(path);
  • If the directory already exists, an exception FileAlreadyExistsException will be thrown
  • You cannot create a multi-level directory at one time, otherwise NoSuchFileException will be thrown

Create multi-level directories with

Path path = Paths.get("helloword/d1/d2");  // 即使d1目录不能存在也会创建出来
Files.createDirectories(path);

copy files

Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/target.txt");

Files.copy(source, target);  // 从source 拷贝到 target
  • If the file already exists, an exception FileAlreadyExistsException will be thrown

If you want to overwrite the target with source, you need to use StandardCopyOption to control

Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

If you want to copy files, use this copy or transferTo, both of which are more efficient

move files

Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/data.txt");

Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
  • StandardCopyOption.ATOMIC_MOVE guarantees the atomicity of file movement

Delete Files

Path target = Paths.get("helloword/target.txt");

Files.delete(target);
  • If the file does not exist, an exception NoSuchFileException will be thrown

Delete directory (can only delete an empty directory)

Path target = Paths.get("helloword/d1");

Files.delete(target);
  • If the directory still has content, an exception DirectoryNotEmptyException will be thrown

Traversing directory files

public static void main(String[] args) throws IOException {
    
    
    Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");   // 遍历的其实文件
    AtomicInteger dirCount = new AtomicInteger();
    AtomicInteger fileCount = new AtomicInteger();
    //                       这里的代码模式用到了访问者模式,你要做的操作就通过访问者来加入你的逻辑即可
    Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    
    
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) 
            throws IOException {
    
    
            System.out.println(dir);
            dirCount.incrementAndGet();  // +1   
            // 注意这里是匿名内部类里的,所以不能用 在外面的 int 来 ++,匿名类要应用外部局部变量实质是个常量来的,是不能改变它的值的
            // 要用要用累加器来计算
            return super.preVisitDirectory(dir, attrs);
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
            throws IOException {
    
    
            System.out.println(file);
            fileCount.incrementAndGet();
            return super.visitFile(file, attrs);
        }
    });
    System.out.println(dirCount); // 133
    System.out.println(fileCount); // 1479
}

Count the number of jars

Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");
AtomicInteger fileCount = new AtomicInteger();
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    
    
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
        throws IOException {
    
    
        if (file.toFile().getName().endsWith(".jar")) {
    
    
            fileCount.incrementAndGet();
        }
        return super.visitFile(file, attrs);
    }
});
System.out.println(fileCount); // 724

Delete multi-level directories

Path path = Paths.get("d:\\a");
Files.walkFileTree(path, 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);
    }
});

⚠️ Deleting is dangerous

Deletion is a dangerous operation, make sure the folder to be deleted recursively has no important content

Copy multi-level directories

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

        long start = System.currentTimeMillis();
        String source = "F:\\aaaa";     // 被拷贝的原始目录
        String target = "F:\\bbbb";
        //          起始路径 Paths.get(source)返回的是一个Stream流,所以我们可以用Stream流对应的一些 api 来进行操作
        //                                    path : 就是遍历到的文件目录
        Files.walk(Paths.get(source)).forEach(path -> {
    
    
            try {
    
    

                System.out.println( " 遍历到的 =====》" +  path );

                // targerName就是最终要操作的目录
                /*
                 source 目录被替换成target目录,比如 source = F:\\aaaa, target = "F:\\bbbb"
                 那么再拷贝 D:\\aaaa\\bb.txt时,就需要替换成 D:\\bbbb\\bb.txt,即source部分被替换成target
                 */
                String targetName = path.toString().replace(source, target);
                System.out.println( "替换后的 ------>" +  targetName );
                // 是目录
                if (Files.isDirectory(path)) {
    
    
                    Files.createDirectory(Paths.get(targetName));
                }
                // 是普通文件
                else if (Files.isRegularFile(path)) {
    
    
                    // 把
                    Files.copy(path, Paths.get(targetName));
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        });
        long end = System.currentTimeMillis();
        System.out.println( "花时 : " + (end - start)+ "ms" );
    }
}

Output when running:
[External link image transfer failed, the source site may have an anti-leech mechanism, it is recommended to save the image and upload it directly (img-36vxpC0K-1673630241801)[External link image transfer failed, the source site may have an anti-leech mechanism, it is recommended to save the image Download directly (img-TMVDfrZw-1673630255597)(../../RunningYuBlog/source/images/image-20230114011523888.png)]

copied bbbb
[External link image transfer failed, the source site may have an anti-leech mechanism, it is recommended to save the image and upload it directly (img-C0aZTxK3-1673630241803) [External link image transfer failed, the source site may have an anti-leech mechanism, it is recommended to save the image Download directly (img-Y0fAIUOE-1673630263761)(../../RunningYuBlog/source/images/image-20230114011547604.png)]

Guess you like

Origin blog.csdn.net/QRLYLETITBE/article/details/128681657