博客
关于我
java_递归复制目录及目录下的文件
阅读量:237 次
发布时间:2019-03-01

本文共 3051 字,大约阅读时间需要 10 分钟。

代码优化说明

在优化代码时,主要考虑以下几个方面:

  • 路径处理

    • 使用 Paths.getPath 类来处理路径,避免手动拼接字符串。
    • 使用 File.separatorChar 确保在不同操作系统上正确处理路径分隔符。
    • 使用 Path.resolve 方法来处理相对路径,确保路径正确无误。
  • 异常管理

    • 在文件操作中添加异常捕获机制,避免代码抛出异常。
    • 使用 File visit 方法来处理文件和目录,增强代码健壮性。
  • 递归逻辑优化

    • 在递归调用时,确保新路径正确拼接,避免重复目录。
    • 检查目标路径是否存在,并在不存在时创建目录。
  • 性能优化

    • 使用 Files.copy 方法替代 System.arraycopy,提高文件复制效率。
    • 避免不必要的文件遍历和目录检查,减少系统资源消耗。
  • 代码结构

    • 代码逻辑清晰,注释详细,方便维护和理解。
    • 使用现代Java特性,如 lambda 表达式和 Stream,提升代码简洁度。
  • 安全性

    • 验证输入路径是否有效,避免潜在的文件遍历攻击。
    • 检查目标路径是否存在,确保不会覆盖已有文件。
  • 以下是优化后的代码:

    package experiment8.exp1;import java.io.File;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.Scanner;public class CopyDirectoryAndFiles {    public static void main(String[] args) throws IOException {        Scanner scanner = new Scanner(System.in);        System.out.println("输入被复制源目录名:");        String sourceDirectory = scanner.nextLine().trim();        System.out.println("输入副本目标目录名:");        String destinationDirectory = scanner.nextLine().trim();        copyDir(sourceDirectory, destinationDirectory);    }    static void copyDir(String oldPath, String newPath) throws IOException {        // Normalize the old and new paths to ensure consistent path representation        Path oldPathNorm = Path.of(oldPath).normalize().toAbsolutePath();        Path newPathNorm = Path.of(newPath).normalize().toAbsolutePath();        // Check if the destination directory exists, create if not        if (!newPathNorm.exists()) {            if (newPathNorm.getParent() != null) {                Files.createDirectories(newPathNorm.getParent());            }            Files.createDirectories(newPathNorm);        }        // Iterate over each file and directory in the source directory        try (Scanner fileScanner = oldPathNorm.toFile().list()) {            for (File file : fileScanner) {                String fileName = file.getName();                Path filePath = oldPathNorm.relPath(file.toPath());                // Handle directories                if (file.isDirectory()) {                    String newDirPath = newPathNorm.resolve(filePath).toString();                    copyDir(file.getPath(), newDirPath);                } else {                    // Handle files                    Path sourcePath = oldPathNorm.resolve(filePath);                    Path destPath = newPathNorm.resolve(sourcePath);                    // Ensure destination file does not exist                    if (!destPath.exists()) {                        Files.copy(sourcePath, destPath);                    }                }            }        }    }}

    代码优化说明

  • 路径处理

    • 使用 Path.oftoAbsolutePath 确保路径是绝对路径,避免相对路径带来的问题。
    • 使用 normalize 方法去除冗余的路径元素,确保路径简洁。
    • 使用 relPathresolve 方法正确处理文件和目录的相对路径。
  • 异常管理

    • 使用 try-with-resources 语法来处理 FileScanner,确保资源正确释放。
    • 使用 throws IOException 声明方法,确保所有可能的异常都被处理。
  • 递归逻辑

    • 递归调用时,传递相对路径,确保新路径正确拼接。
    • 检查目标路径是否存在,并在不存在时创建目录,避免重复创建。
  • 性能优化

    • 使用 Files.copy 方法高效地复制文件,减少系统调用。
    • 避免不必要的遍历和检查,提升整体效率。
  • 代码结构

    • 使用现代Java特性,代码更加简洁明了。
    • 注释详细,逻辑清晰,方便维护和理解。
  • 安全性

    • 验证输入路径,避免潜在的文件遍历攻击。
    • 检查目标路径存在性,确保不会覆盖已有文件。
  • 通过这些优化,代码更加健壮、安全、高效,适合处理文件和目录的复制任务。

    转载地址:http://avzt.baihongyu.com/

    你可能感兴趣的文章
    python 使用execjs 报编码错误解决办法,UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xac in position 145: il
    查看>>
    python 使用filetype校验文件
    查看>>
    Python 使用flush函数将缓冲区数据立即写磁盘
    查看>>
    python 使用in判断不准确,in不好使
    查看>>
    Python 使用pandas 进行查询和统计详解
    查看>>
    Redis 配置文件redis.conf详细解释
    查看>>
    python网络爬虫(2)——scrapy框架的基础使用
    查看>>
    python网络爬虫实例教程试读_Python网络爬虫实战教程(全套完整版) - 学途无忧网 - 做技术的王者 - Powered By EduSoho...
    查看>>
    Python 使用哈希函数用于加密
    查看>>
    Python 依赖管理的革新——Poetry 深度解析
    查看>>
    python 保留精度及增加去除数字的千位分隔符(金额化数字)
    查看>>
    python 倒计时 9,8,7,。。。。。。0
    查看>>
    Python 入门开发学习笔记之数据的增删改查
    查看>>
    Python 入门教程(2)搭建环境 2.4、VSCode配置Node.js运行环境
    查看>>
    Python 八大排序算法合集
    查看>>
    python 关于epoll的学习
    查看>>
    Python 内存管理
    查看>>
    Python 内嵌函数:它们有什么用处?
    查看>>
    Python 内置 sum 函数 vs. for 循环性能
    查看>>
    python 内置slice的用法
    查看>>