需求:
将文件目录下的视频01、02...改为19、20...
代码:
简单实现代码:
import java.io.File;
public class Test {
public static void main(String[] args) {
File dir=new File("E:\\heimalearn\\aaa");
//1.拿到下面的全部视频,一级文件对象
File[] videos = dir.listFiles();
//2.一个一个的找
for (File video : videos) {
//3.拿到它的名字,改成新名字
String name=video.getName();
String index=name.substring(0,name.indexOf("_"));
String lastName=name.substring(name.indexOf("."));
String newName=(Integer.valueOf(index)+18)+lastName;
//4.正式改名
video.renameTo(new File(dir,newName));
}
}
}
扩展的代码(回头看):
import java.io.File;
public class Test0306 {
public static void main(String[] args) {
// 指定文件夹路径
String folderPath = "E:\\heimalearn\\aaa";
File folder = new File(folderPath);
// 获取文件夹中的所有文件
File[] files = folder.listFiles();
if (files != null) {
int startNumber = 1; // 起始序号
for (File file : files) {
if (file.isFile() && isVideoFile(file)) {
// 获取文件扩展名
String extension = getFileExtension(file);
// 构建新的文件名
String newFileName = String.format("%03d.%s", startNumber, extension);//_改成了.应该是""里的原因,但是别乱改,_后面直接全没了
File newFile = new File(folderPath + File.separator + newFileName);
// 重命名文件
if (file.renameTo(newFile)) {
System.out.println("Renamed: " + file.getName() + " -> " + newFileName);
startNumber++;
} else {
System.out.println("Failed to rename: " + file.getName());
}
}
}
} else {
System.out.println("The folder is empty or does not exist.");
}
}
// 判断文件是否为视频文件
private static boolean isVideoFile(File file) {
String[] videoExtensions = {".mp4", ".avi", ".mkv", ".mov", ".flv"};
String fileName = file.getName().toLowerCase();
for (String ext : videoExtensions) {
if (fileName.endsWith(ext)) {
return true;
}
}
return false;
}
// 获取文件扩展名
private static String getFileExtension(File file) {
String fileName = file.getName();
int lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex != -1) {
return fileName.substring(lastDotIndex + 1);
}
return "";
}
}