6.Files,Paths工具类

Path用来表示文件路径

Paths是工具类,用来获取Path实例。

Files.copy方法

/**
     * 拷贝文件,效率高 跟 transferTo方法传输文件效率差不多
     */
    public static void  copyFile() {
        Path sourcePath = Paths.get("text.txt");
        Path targetPath = Paths.get("3.txt");
        try {
            //如果目标文件已经存在,不能覆盖文件,会抛出FileAlreadyExistsException
            Files.copy(sourcePath, targetPath);
            //如果向覆盖目标文件,多添加一个参数
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
package com.xkj.org.file;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class WalkFileTreeDemo {

    /**
     * 遍历文件夹的所有文件,采用非递归的方式,遍历文件树
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
//        walkFileTreeMethod();
//        walkFileTreeMethod2();
//        delete();
//        delByWalkFileTree();
        copyFilesAndDir();


    }

    /**
     * 把一个文件夹里的子文件夹和文件拷贝到另一个文件夹中
     * @throws IOException
     */
    private static void copyFilesAndDir() throws IOException {
        String source = "D:\\自考资料";
        String target = "D:\\自考资料copy";
        Files.walk(Paths.get(source)).forEach(path -> {
            try {
                String targetName = path.toString().replace(source, target);
                if(Files.isDirectory(path)) {
                    //是目录
                    //创建目录
                    Files.createDirectory(Paths.get(targetName));
                }else if(Files.isRegularFile(path)) {
                    //是文件
                    //拷贝文件
                    Files.copy(path, Paths.get(targetName));
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 删除文件夹及其子文件夹和文件
     * @throws IOException
     */
    private static void delByWalkFileTree() throws IOException {
        Files.walkFileTree(Paths.get("D:\\test"), 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 delete() throws IOException {
        //删除的文件夹如果不为空是不能删除的,抛出异常DirectoryNotEmptyException
        Files.delete(Paths.get("D:\\test"));
    }

    /**
     * 遍历所有文件,获取jar文件,并统计数量
     * @throws IOException
     */
    private static void walkFileTreeMethod2() throws IOException {

        AtomicInteger jarCount = new AtomicInteger();

        Files.walkFileTree(Paths.get("D:\\devTools\\Java\\jdk1.8.0_321"), new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if(file.toString().endsWith(".jar")) {
                    log.info("jar file={}", file);
                    jarCount.incrementAndGet();
                }
                return super.visitFile(file, attrs);
            }
        });
        log.info("jar file count={}", jarCount);
    }


    /**
     * 遍历所有的文件夹和文件,分别统计数量
     * @throws IOException
     */
    private static void walkFileTreeMethod() throws IOException {
        //文件夹数量,这里使用累加器而不能使用局部变量。
        //因为局部变量要在匿名内部类中使用,必须定义为final修饰,那么变量就不能被修改了。
        AtomicInteger dirCount = new AtomicInteger();
        //文件数量
        AtomicInteger fileCount = new AtomicInteger();

        Files.walkFileTree(Paths.get("D:\\devTools\\Java\\jdk1.8.0_321"), new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                log.info("dir={}", dir);
                dirCount.incrementAndGet();
                //这个父类的返回值不能删除,否则遍历会失效
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                log.info("file={}", file);
                fileCount.incrementAndGet();
                //这个父类的返回值不能删除,否则遍历会失效
                return super.visitFile(file, attrs);
            }
        });

        log.info("文件夹的数量={}", dirCount);
        log.info("文件的数量={}", fileCount);
    }

}

相关推荐

  1. 6.Files,Paths工具

    2024-03-31 04:28:05       38 阅读
  2. 工具】对象比较工具实现

    2024-03-31 04:28:05       21 阅读
  3. webrtc 工具

    2024-03-31 04:28:05       55 阅读
  4. HttpUtils工具

    2024-03-31 04:28:05       56 阅读
  5. date工具

    2024-03-31 04:28:05       52 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-31 04:28:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-31 04:28:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-31 04:28:05       82 阅读
  4. Python语言-面向对象

    2024-03-31 04:28:05       91 阅读

热门阅读

  1. 黑豹程序员-vue3 setup 子组件给父组件传值

    2024-03-31 04:28:05       36 阅读
  2. ASP .NET 中控制器获取数据的方法

    2024-03-31 04:28:05       31 阅读
  3. P8772 [蓝桥杯 2022 省 A] 求和

    2024-03-31 04:28:05       36 阅读
  4. 拯救者r9000 ubuntu20 屏幕亮度无法调节

    2024-03-31 04:28:05       89 阅读
  5. 蓝桥杯每日不知道多少题之翻硬币递增三元组

    2024-03-31 04:28:05       35 阅读
  6. 联想笔试(0328)

    2024-03-31 04:28:05       43 阅读
  7. redis

    redis

    2024-03-31 04:28:05      36 阅读
  8. playwright 对象是 Playwright 框架中的核心对象

    2024-03-31 04:28:05       40 阅读
  9. php 快速入门(五)

    2024-03-31 04:28:05       36 阅读
  10. 顺序表专题

    2024-03-31 04:28:05       37 阅读
  11. HTTP和tcp的区别

    2024-03-31 04:28:05       37 阅读
  12. Git版本管理使用手册 - 5 - Git的.ignore文件语法

    2024-03-31 04:28:05       36 阅读