java定时删除tomcat目录下的文件

1、在web.xml中添加监听器

<listener>
    <listener-class>
         com.ydtf.oms.action.monitor.action.excelListener.ExcelTempFileListener
    </listener-class>
</listener>
2、execl.properties
#配置服务器excel文件存放的时间,以分钟为单位一天可以这样表示 :1440(60*24)为一天,等以此类推  
#10080分钟,删除一周前的文件
file_retention_time=10080
#1440分钟,一天执行一次
every_time_run=1440
3、java类

package com.ydtf.oms.action.monitor.action.excelListener;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


/**
 * 时间监听器
 * 
 * @author shixf
 * 
 */
public class ExcelTempFileListener implements ServletContextListener {

	private Timer timer;
	private SystemTaskTest systemTask;
	private static String every_time_run;
	static {
		Properties prop = new Properties();
		InputStream inStrem = ExcelTempFileManager.class.getClassLoader()
				.getResourceAsStream("execl.properties");
		try {
			prop.load(inStrem);
			every_time_run = prop.getProperty("every_time_run");

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				inStrem.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	// 监听器初始方法
	public void contextInitialized(ServletContextEvent sce) {
		timer = new Timer();
		systemTask = new SystemTaskTest(sce.getServletContext()
				.getRealPath("/"), sce.getServletContext());
		try {
			sce.getServletContext().log("定时器已启动");
			String s = "2018-1-8 17:12:00";  
		    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		    Date d = format.parse(s);
			// 设置在每晚24:0分执行任务
			// Calendar calendar = Calendar.getInstance();
			// //calendar.set(Calendar.HOUR_OF_DAY, 24); // 24 ,可以更改时间
			// calendar.set(Calendar.MINUTE, 28); // 0可以更改分数
			// calendar.set(Calendar.SECOND, 0);// 0 //默认为0,不以秒计
			// Date date = calendar.getTime();
			// 监听器获取网站的根目录
			String path = sce.getServletContext().getRealPath("/");
			   // dstPath = ServletActionContext.getServletContext().getRealPath("/uploadNewTemplate/")+ "\\" + excelName;
			Long time = Long.parseLong(every_time_run) *60 * 1000;// 循环执行的时间
			//System.out.println("time" + time);
			// 第一个参数是要运行的代码,第二个参数是指定时间执行,只执行一次
			// timer.schedule(systemTask,time);
			// 第一个参数是要运行的代码,第二个参数是从什么时候开始运行,第三个参数是每隔多久在运行一次。重复执行
			timer.schedule(systemTask, d, time);
			sce.getServletContext().log("已经添加任务调度表");
		} catch (Exception e) {
		}

	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		try {
			timer.cancel();
		} catch (Exception e) {
		}
	}

}
package com.ydtf.oms.action.monitor.action.excelListener;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * 删除服务器上的文件
 * 实现Runnable接口(推荐),可以线程接口,预留一个extends(继承),方便扩展
 * 
 * @author shixf
 */
public class ExcelTempFileManager implements Runnable {

	private static String path;// 路径

	private static String RETENTION_TIME = "";// 文件保存的时间
	static {
		Properties prop = new Properties();
		InputStream inStrem = ExcelTempFileManager.class.getClassLoader()
				.getResourceAsStream("execl.properties");
		try {
			prop.load(inStrem);
			RETENTION_TIME = prop.getProperty("file_retention_time");

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				inStrem.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 构造函数。初始化参数
	 * 
	 * @param path
	 */
	public ExcelTempFileManager(String path) {
		this.path = path;
	}

	/**
	 * 把线程要执行的代码放在run()中
	 */
	@Override
	public void run() {
		path = path + "uploadNewTemplate";
		File file = new File(path);
		deletefiles(file);
	}

	/**
	 * 批量删除文件
	 * 
	 * @param folder
	 */
	public void deletefiles(File folder) {
		File[] files = folder.listFiles();
		for (int i = 0; i < files.length; i++) {
			deleteFile(files[i]);
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param file
	 */
	private void deleteFile(File file) {
		try {
			if (file.isFile()) {
				// 删除符合条件的文件
				if (canDeleteFile(file)) {
					if (file.delete()) {
						System.out.println("文件" + file.getName() + "删除成功!");
					} else {
						System.out.println("文件" + file.getName() + "删除失败!此文件可能正在被使用");
					}
				} else {

				}
			} else {
				System.out.println("没有可以删除的文件了");
			}

		} catch (Exception e) {
			System.out.println("删除文件失败========");
			e.printStackTrace();
		}
	}

	/**
	 * 判断文件是否能够被删除(删除一周前的文件)
	 */
	private boolean canDeleteFile(File file) {
		Date fileDate = getfileDate(file);
		Date date = new Date();
		long time = (date.getTime() - fileDate.getTime()) / 1000 / 60
				- Integer.parseInt(RETENTION_TIME);// 当前时间与文件间隔的分钟
		if (time > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取文件最后的修改时间
	 * 
	 * @param file
	 * @return
	 */
	private Date getfileDate(File file) {
		long modifiedTime = file.lastModified();
		Date d = new Date(modifiedTime);
		return d;
	}

	/**
	 * 格式化日期,没有用到
	 */
	private String formatDate(Date date) {
		// SimpleDateFormat f=new SimpleDateFormat("yyyyMMdd hh:mm:ss");//12小时制
		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd HH:mm:ss");// 24小时制
		String formateDate = f.format(date);
		return formateDate;
	}

	/**
	 * 删除文件夹
	 * 
	 * @param folder
	 */
	public void deleteFolder(File folder) {
		if (folder.isDirectory()) {
			File[] files = folder.listFiles();
			for (int i = 0; i < files.length; i++) {
				deleteFolder(files[i]);
			}

			// 非当前目录,删除
			if (!folder.getAbsolutePath().equalsIgnoreCase(path)) {

				// 只删除在30分钟前创建的文件
				if (canDeleteFile(folder)) {
					if (folder.delete()) {
						System.out.println("文件夹" + folder.getName() + "删除成功!");
					} else {
						System.out.println("文件夹" + folder.getName()
								+ "删除失败!此文件夹内的文件可能正在被使用");
					}
				}
			}
		} else {
			deleteFile(folder);
		}
	}

}

package com.ydtf.oms.action.monitor.action.excelListener;

import java.util.Date;
import java.util.TimerTask;

import javax.servlet.ServletContext;

/**
 * 时间任务器
 * @author shixf
 *
 */
public class SystemTaskTest extends TimerTask {

	private ServletContext context;  
    private String path;  
    private static String every_time_run;  
    public SystemTaskTest(String path, ServletContext context) {  
        this.path = path;  
        this.context = context;  
    }  
    
	@Override
	/**  
     * 把要定时执行的任务就在run中  
     */  
	public void run() {
		ExcelTempFileManager etf;     
        try {  
            context.log("开始执行任务!");  
            // 需要执行的代码  
            System.out.println(new Date().toLocaleString());  
            System.out.println("path======" + path);  
            etf = new ExcelTempFileManager(path);  
            etf.run();        
            context.log("指定任务执行完成!");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  

	}

}
4、目录

5、参考网址

http://blog.csdn.net/lintianlin/article/details/40540831

http://blog.csdn.net/bestcxx/article/details/50298637

http://blog.csdn.net/u012750578/article/details/17346529

https://www.cnblogs.com/hongwz/p/5642429.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章