【Java文件管理】测试删除文件速度的几种方法

1. 代码里包含了先创建文件,再删除文件

package com.api.apidemo.tool.file;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Comparator;
import java.util.Random;

/**
 * @author cathay10
 * @description 批量删除文件性能测试
 */
public class BatchDeleteFilePerformance {

    /**
     * 文件路径
     */
    public static String filePath = "/home/cathay10/workSpace/log";

    /**
     * 生成文件夹深度
     */
    static int folderMaxDepth = 5;

    /**
     * 每层文件夹数量
     */
    static int folderCount = 10;

    /**
     * 每层文件数量
     */
    static int fileCount = 10;

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Path path = Paths.get(filePath);
        createFolder(path, 0, folderCount);
        long end = System.currentTimeMillis();
        System.out.println("创建文件耗时:" + (end - start) + "ms");


        start = System.currentTimeMillis();
        deleteFile_3(filePath);
        end = System.currentTimeMillis();
        System.out.println("删除文件耗时:" + (end - start) + "ms");
    }

    /**
     * 删除文件夹及其子文件,使用Files.walk()遍历文件树,并使用Files.delete()删除文件
     *
     * @param path
     */
    public static void deleteFile_1(String path) {
        Path dirPath = Paths.get(path);
        try {
            Files.walk(dirPath)
                    .sorted(Comparator.reverseOrder())
//                    .map(Path::toFile)
                    .forEach(BatchDeleteFilePerformance::deleteDirectoryStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void deleteDirectoryStream(Path path) {
        try {
            Files.delete(path);
//            System.out.printf("删除文件成功:%s%n",path.toString());
        } catch (IOException e) {
//            System.err.printf("无法删除的路径 %s%n%s", path, e);
        }
    }

    /**
     * 删除文件夹及其子文件,使用for循环遍历文件树,并使用File.delete()删除文件
     *
     * @param path
     */
    public static void deleteFile_2(String path) {
        File directory = new File(path);
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                file.delete();
            } else {
                deleteFile_2(file.getAbsolutePath());
                file.delete();
            }
        }
        directory.delete();
    }

    /**
     * 删除文件夹及其子文件,使用Files.walk()遍历文件树,并使用File.delete()删除文件
     *
     * @param path
     */
    public static void deleteFile_3(String path) {
        Path dirPath = Paths.get(path);
        try {
            Files.walk(dirPath)
                    .sorted(Comparator.reverseOrder())
                    .map(Path::toFile)
                    .forEach(File::delete);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件夹及其子文件,使用Files.walkFileTree()遍历文件树,并使用Files.delete()删除文件
     *
     * @param path
     */
    public static void deleteFile_4(String path) {
        Path dirPath = Paths.get(path);
        try {
            Files.walkFileTree(dirPath, new SimpleFileVisitor<Path>() {
                        // 先去遍历删除文件
                        @Override
                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                            Files.delete(file);
//                            System.out.printf("文件被删除 : %s%n", file);
                            return FileVisitResult.CONTINUE;
                        }

                        // 再去遍历删除目录
                        @Override
                        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                            Files.delete(dir);
//                            System.out.printf("文件夹被删除: %s%n", dir);
                            return FileVisitResult.CONTINUE;
                        }
                    }
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建文件夹
     *
     * @param path        初始路径文件
     * @param folderDepth 深度
     * @param folderCount 文件夹数量
     */
    public static void createFolder(Path path, int folderDepth, int folderCount) {
        if (folderDepth != 0) {
            path = randomFolderName(path);
        }
        try {
            Files.createDirectories(path);
            ++folderDepth;
            for (int i = 1; i <= folderCount; i++) {
                if (folderDepth < folderMaxDepth) {
                    createFolder(path, folderDepth, folderCount);
                }
            }
            if (folderDepth == folderMaxDepth) {
                createFile(path);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建文件
     *
     * @param path 文件路径
     */
    public static void createFile(Path path) {
        for (int i = 0; i < fileCount; i++) {
            Path filePath = randomFileName(path);
            // 创建文件
            try (FileWriter writer = new FileWriter(filePath.toFile())) {
                // 1MB的字符数组
                char[] buffer = new char[1024];
                StringBuilder sb = new StringBuilder(buffer.length);
                for (int x = 0; x < buffer.length; x++) {
                    // 填充字符
                    sb.append('X');
                }
                String content = sb.toString();
                // 转换为字节
                long bytesToWrite = 1024;
                while (bytesToWrite > 0) {
                    writer.write(content);
                    bytesToWrite -= content.getBytes().length;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 生成随机字符串
     *
     * @param length 字符串长度
     * @return 随机字符串
     */
    public static String randomString(int length) {
        String letters = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        String result = "";

        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(letters.length());
            result += letters.charAt(index);
        }
        return result;
    }

    /**
     * 生成文件名,如果文件名已存在,则重新生成
     */
    public static Path randomFileName(Path dirPath) {
        Path filePath = dirPath.resolve(randomString(6) + ".txt");
        File file = filePath.toFile();
        if (file.exists()) {
            filePath = randomFileName(dirPath);
        }
        return filePath;
    }

    /**
     * 生成文件夹名,如果文件夹名已存在,则重新生成
     */
    public static Path randomFolderName(Path dirPath) {
        Path filePath = dirPath.resolve(randomString(6));
        File file = filePath.toFile();
        if (file.exists()) {
            filePath = randomFileName(dirPath);
        }
        return filePath;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值