文件夹是 2023060200.tar 这种名称,现在要把文件夹名称截取,只是留下 2023060200 这种格式的,批量处理
public static void main(String[] args) {
String folderPath = "D:\\data\\"; // 指定文件夹路径
File folder = new File(folderPath);
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
String oldFolderName = file.getName();
String newFolderName = getNewFolderName(oldFolderName);
renameFolder(file, newFolderName);
}
}
}
}
private static String getNewFolderName(String oldFolderName) {
int dotIndex = oldFolderName.lastIndexOf(".");
if (dotIndex != -1) {
return oldFolderName.substring(0, dotIndex);
} else {
return oldFolderName;
}
}
private static void renameFolder(File folder, String newFolderName) {
File newFolder = new File(folder.getParent(), newFolderName);
if (folder.renameTo(newFolder)) {
System.out.println("Renamed folder: " + folder.getName() + " to " + newFolderName);
} else {
System.out.println("Failed to rename folder: " + folder.getName());
}
}