本文共 3098 字,大约阅读时间需要 10 分钟。
在优化代码时,主要考虑以下几个方面:
路径处理:
Paths.get 和 Path 类来处理路径,避免手动拼接字符串。File.separatorChar 确保在不同操作系统上正确处理路径分隔符。Path.resolve 方法来处理相对路径,确保路径正确无误。异常管理:
File visit 方法来处理文件和目录,增强代码健壮性。递归逻辑优化:
性能优化:
Files.copy 方法替代 System.arraycopy,提高文件复制效率。代码结构:
安全性:
以下是优化后的代码:
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.of 和 toAbsolutePath 确保路径是绝对路径,避免相对路径带来的问题。normalize 方法去除冗余的路径元素,确保路径简洁。relPath 和 resolve 方法正确处理文件和目录的相对路径。异常管理:
try-with-resources 语法来处理 FileScanner,确保资源正确释放。throws IOException 声明方法,确保所有可能的异常都被处理。递归逻辑:
性能优化:
Files.copy 方法高效地复制文件,减少系统调用。代码结构:
安全性:
通过这些优化,代码更加健壮、安全、高效,适合处理文件和目录的复制任务。
转载地址:http://avzt.baihongyu.com/