1、遞歸遍歷文件夾及子文件
2传轰、替換文件夾及文件名稱
上代碼:
private static String TEMPLATE_STR = "account-service";
/**
* 遞歸遍歷文件夾窿克,并替換文件夾及文件的名稱
*
* @param path 遍歷文件夾的起始位置
* @param newPathName 新文件夾或新文件的名稱
*/
public void foreachAndReplaceFolder(String path, String newPathName) {
File folder = new File(path);
if (!folder.exists()) {
log.info("文件不存在! path=" + path);
return;
}
File[] fileArr = folder.listFiles();
if (null == fileArr || fileArr.length == 0) {
log.info("文件夾是空的! path=" + path);
return;
}
for (File file : fileArr) {
//若是文件夾洲敢,替換文件夾沉桌,
if (file.isDirectory()) {
//判斷文件夾是否包含指定字符串坦冠,
if (file.getName().contains(TEMPLATE_STR)) {
log.info("替換舊文件夾:{}", file.getName());
String newFilePath = file.getParent() + System.getProperty("file.separator") + file.getName().replaceAll(TEMPLATE_STR, newPathName);
file.renameTo(new File(newFilePath));
foreachAndReplaceFolder(newFilePath, newPathName);
} else {
//不包含领迈,繼續(xù)遞歸
foreachAndReplaceFolder(file.getAbsolutePath(), newPathName);
}
} else {
//是文件彻磁,判斷文件名稱是否包含指定字符串碍沐,
if (file.getName().contains(TEMPLATE_STR)) {
String newFilePath = file.getParent() + System.getProperty("file.separator") + file.getName().replaceAll(TEMPLATE_STR, newPathName);
file.renameTo(new File(newFilePath));
log.info("替換舊文件:" + file.getName());
}
}
}
}