1 import java.io.File; 2 import java.text.ParseException; 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 import java.util.Timer; 6 import java.util.TimerTask; 7 8 /* 9 * :在指定的时间删除指定目录 10 * 设置为一个计时任务 11 */ 12 public class TimerTest { 13 public static void main(String[] args) throws Exception { 14 Timer t = new Timer(); 15 16 String s = "2016-04-09 20:46:59"; 17 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 18 Date d = sdf.parse(s); 19 20 t.schedule(new DeleteFolder(), d); 21 } 22 } 23 24 class DeleteFolder extends TimerTask { 25 @Override 26 public void run() { 27 File srcFolder = new File("demo"); 28 deleteFolder(srcFolder); 29 } 30 31 private void deleteFolder(File srcFolder) { 32 File[] fileArr = srcFolder.listFiles(); 33 if (fileArr != null) { 34 for (File file : fileArr) { 35 if (file.isDirectory()) { 36 deleteFolder(file); 37 } else { 38 file.delete(); 39 } 40 } 41 } 42 // 该语句用于当文件夹已经为空时,直接将文件夹删除。 43 srcFolder.delete(); 44 } 45 }