Don’t say much, just go to the code.
package org.bood.common.utils;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
/**
* 文件重命名
*
* @author bood
* @since 2024/12/02
*/
public class FileRenamer {
public static void main(String[] args) {
// 替换为实际的目录路径
String directoryPath = "path/to/your/directory";
try {
renameFilesInDirectory(directoryPath);
} catch (Exception e) {
e.printStackTrace();
}
try {
char targetChar = 'a';
char replacementChar = 'b';
replaceCharInFilenames(directoryPath, targetChar, replacementChar);
} catch (Exception e) {
e.printStackTrace();
}
try {
renameFilesByCreationTime(directoryPath);
} catch (Exception e) {
e.printStackTrace();
}
try {
organizeFilesByCreationYear(directoryPath);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 处理指定目录下的所有文件,先去掉文件名中的所有空格,然后在连字符 '-' 的前后加上空格。
*
* @param dirPath 要处理的目录路径
* @author bood
* @since 2024/12/02
*/
public static void renameFilesInDirectory(String dirPath) throws IOException {
Path dir = Paths.get(dirPath);
// 检查路径是否存在且是一个目录
if (!Files.exists(dir) || !Files.isDirectory(dir)) {
throw new IllegalArgumentException("提供的路径不是一个有效的目录: " + dirPath);
}
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String originalFileName = file.getFileName().toString();
String newFileName = modifyFileName(originalFileName);
// 如果文件名没有改变,则跳过
if (!originalFileName.equals(newFileName)) {
Path newFilePath = file.resolveSibling(newFileName);
// 重命名文件
Files.move(file, newFilePath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Renamed: " + originalFileName + " -> " + newFileName);
}
return FileVisitResult.CONTINUE;
}
private String modifyFileName(String fileName) {
// 去掉文件名中的所有空格
String noSpaces = fileName.replaceAll("\\s+", "");
// 在连字符'-'的前后加上空格
return noSpaces.replaceAll("(-)", " $1 ");
}
});
}
/**
* 处理指定目录下的所有文件,将文件名中的指定字符替换为另一个字符。
*
* @param dirPath 要处理的目录路径
* @param targetChar 要被替换的字符
* @param replacementChar 用来替换的字符
* @author bood
* @since 2024/12/02
*/
public static void replaceCharInFilenames(String dirPath, char targetChar, char replacementChar) throws IOException {
Path dir = Paths.get(dirPath);
// 检查路径是否存在且是一个目录
if (!Files.exists(dir) || !Files.isDirectory(dir)) {
throw new IllegalArgumentException("提供的路径不是一个有效的目录: " + dirPath);
}
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String originalFileName = file.getFileName().toString();
String newFileName = modifyFileName(originalFileName, targetChar, replacementChar);
// 如果文件名没有改变,则跳过
if (!originalFileName.equals(newFileName)) {
Path newFilePath = file.resolveSibling(newFileName);
// 重命名文件
Files.move(file, newFilePath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Renamed: " + originalFileName + " -> " + newFileName);
}
return FileVisitResult.CONTINUE;
}
private String modifyFileName(String fileName, char targetChar, char replacementChar) {
// 将文件名中的目标字符替换为替代字符
return fileName.replace(targetChar, replacementChar);
}
});
}
/**
* 处理指定目录下的所有文件,将文件名按文件的创建时间命名。
*
* @param dirPath 要处理的目录路径
* @author bood
* @since 2024/12/02
*/
public static void renameFilesByCreationTime(String dirPath) throws IOException {
Path dir = Paths.get(dirPath);
// 检查路径是否存在且是一个目录
if (!Files.exists(dir) || !Files.isDirectory(dir)) {
throw new IllegalArgumentException("提供的路径不是一个有效的目录: " + dirPath);
}
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
try {
// 获取文件的基本属性
BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);
FileTime creationTime = attributes.creationTime();
// 将文件创建时间转换为字符串格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String timeString = sdf.format(new Date(creationTime.toMillis()));
// 构造新的文件名:创建时间 + 原始文件扩展名(如果有)
String originalFileName = file.getFileName().toString();
String extension = "";
int dotIndex = originalFileName.lastIndexOf('.');
if (dotIndex != -1) {
extension = originalFileName.substring(dotIndex);
}
String newFileName = timeString + extension;
// 如果文件名没有改变,则跳过
if (!originalFileName.equals(newFileName)) {
Path newFilePath = file.resolveSibling(newFileName);
// 重命名文件
Files.move(file, newFilePath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Renamed: " + originalFileName + " -> " + newFileName);
}
} catch (IOException e) {
System.err.println("Failed to rename file: " + file + ". Reason: " + e.getMessage());
}
return FileVisitResult.CONTINUE;
}
});
}
/**
* 处理指定目录下的所有文件,按文件的创建年份归纳到相应的子文件夹下。
*
* @param dirPath 要处理的目录路径
* @author bood
* @since 2024/12/02
*/
public static void organizeFilesByCreationYear(String dirPath) throws IOException {
Path dir = Paths.get(dirPath);
// 检查路径是否存在且是一个目录
if (!Files.exists(dir) || !Files.isDirectory(dir)) {
throw new IllegalArgumentException("提供的路径不是一个有效的目录: " + dirPath);
}
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
try {
// 获取文件的基本属性
BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);
FileTime creationTime = attributes.creationTime();
// 将文件创建时间转换为LocalDate
Instant instant = creationTime.toInstant();
LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate();
int year = date.getYear();
// 构造目标年份文件夹路径
Path yearDir = dir.resolve(Integer.toString(year));
// 如果年份文件夹不存在,则创建它
if (!Files.exists(yearDir)) {
Files.createDirectories(yearDir);
System.out.println("Created directory: " + yearDir);
}
// 移动文件到对应的年份文件夹
Path targetFilePath = yearDir.resolve(file.getFileName());
if (!file.equals(targetFilePath)) {
Files.move(file, targetFilePath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Moved: " + file + " -> " + targetFilePath);
}
} catch (IOException e) {
System.err.println("Failed to move file: " + file + ". Reason: " + e.getMessage());
}
return FileVisitResult.CONTINUE;
}
});
}
}
7390

被折叠的 条评论
为什么被折叠?



