1. 批量重命名
java">import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.stream.Stream;
/**
* @author 曹见朋
* @create 2023-10-23-10:02
*/
public class FileBatchRename {
public static void main(String[] args) {
// 设置目录路径
String directoryPath = "D:/example";
// 构建文件路径
Path directory = Paths.get(directoryPath);
try {
// 获取目录下的所有文件
Stream<Path> files = Files.list(directory);
// 遍历所有文件并重命名
files.forEach(file -> {
try {
// 获取文件的名称
String fileName = file.getFileName().toString();
// 新的文件名(可以按需修改)
String newFileName = "new_" + fileName;
// 构建新文件路径
Path newFilePath = directory.resolve(newFileName);
// 执行文件重命名
Files.move(file, newFilePath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Renamed: " + fileName + " to " + newFileName);
} catch (IOException e) {
e.printStackTrace();
}
});
System.out.println("All files have been renamed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上述代码中,我们首先指定了要重命名文件的目录路径。然后,我们使用NIO的Files.list()方法列出目录中的所有文件,并遍历这些文件。在遍历的过程中,可以根据需要修改新的文件名,然后使用Files.move()方法执行文件重命名操作。文件将被重命名为新的名称,然后输出重命名的结果。
2. 批量修改扩展名
java">package com.cjp.bio;
import java.io.File;
/**
* @author 曹见朋
* @create 2023-10-23-9:02
*/
public class BatchRenameFiles {
public static void main(String[] args) {
// 指定目录路径
String directoryPath = "D:/NIO/";
// 旧的文件扩展名
String oldExtension = ".html";
// 新的文件扩展名
String newExtension = ".txt";
// 获取目录下的所有文件
File directory = new File(directoryPath);
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(oldExtension)) {
// 构建新文件名
String newName = file.getName().replace(oldExtension, newExtension);
// 创建新文件对象
File newFile = new File(directoryPath + newName);
// 重命名文件
if (file.renameTo(newFile)) {
System.out.println("Renamed " + file.getName() + " to " + newName);
} else {
System.err.println("Error renaming " + file.getName());
}
}
}
} else {
System.err.println("Directory not found.");
}
}
}