import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;
public class DelFile {
public static void main(String[] args) throws Exception {
// File file = new File("d://a//b");
String delpath = "d://a//b";
deletefile(delpath);
// QuartzManager.addJob("test",TestJob.class,"0 0 1 * * ?");//每天凌晨1点
// QuartzManager.addJob("test",TestJob.class,"*/5 * * * * ?");//每隔5秒钟
// QuartzManager.addJob("test",TestJob.class,"0 */3 * * * ?");//每隔3分钟
}
/**
* 删除某个文件夹下的所有文件夹和文件
*/
public static boolean deletefile(String delpath)
throws FileNotFoundException, IOException {
try {
File file = new File(delpath);
if (!file.isDirectory()) {
System.out.println("1");
file.delete();
} else {
System.out.println("2");
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -2);
Long time = calendar.getTimeInMillis();
/*
* Calendar calendar = Calendar.getInstance(); Long time =
* calendar.getTimeInMillis() - 2 * 60 * 1000;
*/
File rootFile = new File(delpath);
File[] files = rootFile.listFiles();
for (File fil : files) {
if (fil.isDirectory() && fil.lastModified() < time) {
deleteDir(fil);
}
}
}
}
} catch (Exception e) {
System.out.println("deletefile() Exception:" + e.getMessage());
}
return true;
}
private static boolean deleteDir(File dir) {
if (!dir.exists())
return false;
if (dir.isDirectory()) {
String[] childrens = dir.list();
// 递归删除目录中的子目录下
for (String child : childrens) {
boolean success = deleteDir(new File(dir, child));
if (!success)
return false;
}
}
// 目录此时为空,可以删除
return dir.delete();
}
}