package pers.lsy.util.io;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RenameFile {
public static void main(String[] args) {
RenameFile folder = new RenameFile();
String filePath = "";
//替换空格
folder.replaceFileName(new File(filePath),"[/|*|\\\\|?|:|<|>|\\s+]","");
//数字后添加空格
folder.renameFiles(new File(filePath), "\\d*", "");
}
/**
* 重命名文件去除多余文件名字内的文字
*
* @param file 文件
* @param oldName 文件名中需要修改的内容
* @param newName 将需要修改的内容替换为指定内容
*/
public void replaceFileName(File file, String oldName, String newName) {
File[] files = null;
File newfile = null;
if (file.isDirectory()) {
files = file.listFiles();
for (int i = 0; i < files.length; i++) {
renameFiles(files[i], oldName, newName);
}
} else {
// 获取新生成的文件名
// String newstr = file.getAbsolutePath().replaceAll(oldName, newName);
String newstr = file.getName().replaceAll(oldName, newName);
newfile = new File(file.getParent(), newstr);
System.out.println(newfile.getAbsolutePath());
// 重命名文件
file.renameTo(newfile);
}
}
public void renameFiles(File file, String regex, String newName) {
File[] files = null;
File newfile = null;
if (file.isDirectory()) {
files = file.listFiles();
for (int i = 0; i < files.length; i++) {
renameFiles(files[i], regex, newName);
}
} else {
// 获取新生成的文件名
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(file.getName());
if (matcher.find()) {
String newstr = file.getName().replaceAll(regex, newName);
newfile = new File(file.getParent(), matcher.group()+" "+newstr);
System.out.println(newfile.getAbsolutePath());
// 重命名文件
file.renameTo(newfile);
}
}
}
}
02-01
425