package com.lid.servlet; import java.io.File; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Timer; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyTest extends HttpServlet { public MyTest() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {} public void init() throws ServletException { String newDir2 = "D://lidtest"; File dir=new File(newDir2); timer1(dir); } //删除指定路径下的所有文件 public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); //递归删除目录中的子目录下 for (int i=0; i<children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } return true; }else { // 获取文件最后修改时间 Date d = new Date(dir.lastModified()); //获取两天前的时间 Date t = new Date(); Calendar resultDate=Calendar.getInstance(); resultDate.setTime(t); resultDate.add(Calendar.DATE,-2); t = resultDate.getTime(); //删除两天前的文件 if(t.getTime()>=d.getTime()){ return dir.delete(); }else{ return false; } } } //定时执行某任务(每两天执行一次) public static void timer1(File dir) { Timer timer = new Timer(); MyTask myTask=new MyTask(dir); timer.schedule(myTask, 1000, 48*60*60*1000); } }
最近下载更多