import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
void run(){
work();
}
String path="D:\\root";
String[] S=new String[] {"key_word1","key_word2"}; //文件名要删除的关键字
void work() {
File file=new File(path);
dfs(file);
}
private void dfs(File file) {
String cur=file.getAbsolutePath();
String pre=cur;
for(String str:S) {
if(cur.contains(str)) {
int s=cur.lastIndexOf(str);
int e=s+str.length();
cur=cur.substring(0,s)+cur.substring(e);
}
}
if(!pre.equals(cur)) {
File nf=new File(cur);
//file改名之后就不存在了,其内部还是对应原来路径,所以赋一个新的File对象,才能执行下面file.list()方法;
//有时候重名,后者资源被其他进程占用会导致改名失败
boolean f=file.renameTo(nf);
System.out.println("exists="+file.exists());
System.out.println(f);
if(f)file=nf;
}
String[] strs=file.list();
if(strs!=null) {
for(String str:strs) {
File f=new File(cur+"\\"+str);
dfs(f);
}
}
}
}