前言:需求是Java批量处理文件名改为时间戳,并在对应的文件夹里面生成excel,指明文件原文件名及新文件名,方便存储

maven

引入poi

1
2
3
4
5
6
<!-- Apache POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>

编写工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

public class BatchRenameAndLogInExcelUtil {

static class FileInfo {
String oldName;
String newName;

public FileInfo(String oldName, String newName) {
this.oldName = oldName;
this.newName = newName;
}
}

public static void main(String[] args) {
String directoryPath = "D:\\视频"; // 你的目标文件夹路径
File directory = new File(directoryPath);

List<FileInfo> fileInfos = new ArrayList<>();

if (directory.isDirectory()) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
try {
Path filePath = Paths.get(file.getAbsolutePath());
BasicFileAttributes attrs = Files.readAttributes(filePath, BasicFileAttributes.class);
String newFileName = Long.toString(attrs.lastModifiedTime().toMillis()) + getFileExtension(file);
File newFile = new File(directoryPath + File.separator + newFileName);

boolean success = file.renameTo(newFile);
if (success) {
System.out.println(file.getName() + " 重命名为 " + newFileName);
fileInfos.add(new FileInfo(file.getName(), newFileName));
} else {
System.out.println(file.getName() + " 重命名失败");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
System.out.println(directoryPath + " 不是一个目录");
}

// 生成Excel文件
createExcelFile(directoryPath, fileInfos);
}

private static String getFileExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf(".");
if (lastIndexOf == -1) {
return ""; // 空扩展名
}
return name.substring(lastIndexOf);
}

private static void createExcelFile(String directoryPath, List<FileInfo> fileInfos) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("文件重命名日志");

// 创建标题行
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("原文件名");
headerRow.createCell(1).setCellValue("新文件名");

int rowNum = 1;
for (FileInfo fileInfo : fileInfos) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(fileInfo.oldName);
row.createCell(1).setCellValue(fileInfo.newName);
}

// 自动调整列宽
for (int i = 0; i < 2; i++) {
sheet.autoSizeColumn(i);
}

// 写入到文件
try (OutputStream fileOut = new FileOutputStream(directoryPath + File.separator + "文件重命名日志.xlsx")) {
workbook.write(fileOut);
} catch (IOException e) {
e.printStackTrace();
}
}
}