直接可以运行的代码
采用递归方式更改文件,文件夹及子文件夹的文件名称的小工具,以下是代码段 :
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* 重命名规则类
* @author songkangfeng
*/
public class ReplacementChain{
private Map<String,String> map;
public ReplacementChain() {
this.map = new HashMap<String, String>();
}
public Map<String, String> getMap() {
return map;
}
public ReplacementChain addRegulation(String oldStr , String newStr){
this.map.put(oldStr, newStr);
return this;
}
}
/**
* 重命名类
* @author songkangfeng
*/
class Rename {
static int sum = 0;
/**
* 批量重命名
* @param path
* @param replacementChain
*/
public static void multiRename(String path,ReplacementChain replacementChain){
File file = new File(path);
boolean isDirectory = file.isDirectory();
File [] filesArr = file.listFiles();
for(File filesa : filesArr){
if(filesa.isDirectory()&&file.list()!=null&&file.list().length>0){
multiRename(filesa.getPath(), replacementChain);
}
}
String[] files = file.list();
File f = null;
String filename = "";
String oldFileName = "";
/** 循环遍历所有文件* */
for(String fileName : files){
oldFileName = fileName;
Map<String, String> map = replacementChain.getMap();
for (Entry<String, String> entry : map.entrySet()) {
if(fileName.contains(entry.getKey())){
sum++;
}
fileName = fileName.replace(entry.getKey(), entry.getValue());
}
f = new File(path + "\\" + oldFileName);
f.renameTo(new File(path + "\\" + fileName));
}
}
public static void main(String[] args) {
ReplacementChain replacementChain = new ReplacementChain();
replacementChain.addRegulation("oldstr", "newstr");
Rename.multiRename("D:\\Demo", replacementChain);
System.out.println("恭喜,批量重命名成功!共替换"+sum+"个!");
}
}