定时删除临时文件:我定时每天凌晨2点撒删除昨天的临时文件,如果文件的url没有与数据库url相匹配.则删除该文件。
--------为什么我要临时2点删除,头一天的文件?这样有2个小时的时间差,避免删除正在操作用户的临时文件。。
首先写一个监听器实现ServletContextListener接口,在项目启动时执行;
package zy.listener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import zy.utils.DeleteTimer;
import zy.utils.ResourceUtil;
/**
* 定时器删除临时文件
*
* @author Bob
*
*/
public class DeleteTempFileListener implements ServletContextListener {
private static final Logger logger = Logger.getLogger(DeleteTempFileListener.class);
public DeleteTempFileListener() {
}
public void contextInitialized(ServletContextEvent evt) {
//设置定时删除文件的日期
Calendar calendar = Calendar.getInstance();//此时获取的是系统当前时间
calendar.add(Calendar.DATE,1); //得到后一天
String afterdayDate= new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
logger.info("监听删除 昨天上传的临时文件--------------------------------------在每天凌晨2点执行此任务");
//设置定时器每天凌晨2点启动
DateFormat dd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
String after = afterdayDate+" 02:00:00";
date = dd.parse(after);
} catch (ParseException e) {
e.printStackTrace();
}
//第一步获取项目路径头sshy/upload/ ; 格式: 项目名称/文件根文件夹/
String savePath = evt.getServletContext().getRealPath("/") + ResourceUtil.getUploadDirectory() + "/";// 文件保存目录路径
DeleteTimer t = new DeleteTimer();
t.setSavePath(savePath);
Timer timer = new Timer();
timer.schedule(new DeleteTimer(), date, 24*60*60*1000);//在每天凌晨2点执行此任务
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
}
}
接着:配置监听器在web.xml中:
<!-- 删除临时文件监听器 -->
< listener >
<listener-class>zy.listener.DeleteTempFileListener</listener-class>
< listener >
定时器继承TimerTask类:
下文中我都是针对我保存文件路径进行解析的:
文件路径:D:\JDK_Tomcat\Tomcat6.0.33\apache-tomcat-6.0.33\webapps\sshy\upload\04\29\7db7c1df56ad4abc94f4fabf0d01137a.jpg
数据库url所在文章:
" test<img src="/sshy/upload/jpg/2013/04/30/d58fb60006cf42aea40b6fc9055221c7.jpg" alt="" />testtestsdssdfsdfdf
<a href="/sshy/upload/rar/2013/04/30/1d9ca9d0726e45b989463684ebf98e7d.rar">点击打开链接</a>testsdf "
引号内的内容都是我需要解析出url在与现实文件进行对比;
package zy.utils;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import zy.pageModel.Article;
import zy.service.ArticleServiceI;
public class DeleteTimer extends TimerTask implements ApplicationContextAware {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(DeleteTimer.class);
private static ApplicationContext ctx = null;
private ArticleServiceI articleService;
private static String savePath;
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
@Override
public void run() {
String yestedayDate = getDeleteDate();
logger.info("--------------------进行删除日期:"+yestedayDate);
//查询数据库获取当前日期的资源列表
articleService = (ArticleServiceI) ctx.getBean("articleService");
List<Article> list = articleService.findArticleForDate(yestedayDate);
//第一步获取项目路径头sshy/upload/
String split[] = savePath.split("\\\\");
String dir =split[split.length-2]+"/"+split[split.length-1]; //获取到sshy/upload/路径
int len = dir.length()+47;
// Pattern pat = Pattern.compile("webapps.+");
// Matcher mat = pat.matcher(savePath);
// mat.find();
// String dir = mat.group().substring(8); //获取到sshy/upload/路径
//第二步 解析出当天上传至数据库的所有文件的URL
String ext ="(href|src)=/.{"+len+"}\\.{1}[a-zA-Z]{3}";
Pattern pattern = Pattern.compile(ext);
List<String> strList = new ArrayList<String>();
for(int i = 0;i<list.size();i++){
Matcher matcher = pattern.matcher(list.get(i).getCdesc().replaceAll("\"", ""));
//拼接数据库所有的URL,数据库中我只有src与href两种URL
String savePathChange = savePath.substring(0, savePath.length()-1);
while(matcher.find()){
String str= matcher.group(); //格式src=/sshy/upload/jpg/2013/04/28/b4120b5cc87f448780ce5fbc6d5d43f2.jpg
if(str.startsWith("src=")){
strList.add(savePathChange+str.substring(4+dir.length()).replaceAll("/", "\\\\"));
}else{
strList.add(savePathChange+str.substring(5+dir.length()).replaceAll("/", "\\\\"));
}
}
}
finds(savePath,strList);
}
public String getDeleteDate() {
//获取到待删除文件的日期
Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间
calendar.add(Calendar.DATE, -1); //得到前一天的时间
String yestedayDate= new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
return yestedayDate;
}
public void finds(String filePath,List<String> list) {
File file = new File(filePath);
File f[] = null;
f = file.listFiles();
String yestedayDate = getDeleteDate().replaceAll("-", "\\\\"); // 将格式2013-04-28替换成格式:2013\04\28
if(f!=null){ //判断是否具有文件夹
for(int i=0;i<f.length;i++){
if (f[i].isDirectory()) {
finds(f[i].getPath(),list);
}
//获取文件夹指定上传文件夹的目录路径
String deleteDate = null;
String s = f[i].getPath();
Pattern pat = Pattern.compile("[0-9]{4}\\\\[0-9]{2}\\\\[0-9]{2}");
Matcher matcher = pat.matcher(s);
while(matcher.find()){
deleteDate = matcher.group(); // 格式:2013\04\28
}
if(yestedayDate.equals(deleteDate)){ //只遍历删除日期指定文件下的文件
if(f[i].isFile()){
boolean flag = false; //标记判断文件是否存在
for(int j=0;j<list.size();j++){
if(f[i].getPath().equals(list.get(j))){
flag = true ; //文件存在
logger.info(flag+"该文件存在**:"+f[i].getPath());
break; //发现存在终止当前循环;不进行继续对比;切换下一个文件
}
}
if(!flag){ //代表文件不存在
File dfile = new File(f[i].getPath());
if(dfile.delete()){
logger.info("删除文件成功!"+f[i].getPath().toString());
}else{
logger.error("删除文件失败!"+f[i].getPath().toString());
}
}
}
}
}
}
}
@Override
public void setApplicationContext(ApplicationContext contex) throws BeansException {
ctx=contex;
}
}
文件上传对路径的编码:
/**
* 文件上传
*/
public void upload() {
String savePath = ServletActionContext.getServletContext().getRealPath("/") + ResourceUtil.getUploadDirectory() + "/";// 文件保存目录路径
String saveUrl = "/" + ResourceUtil.getUploadDirectory() + "/";// 文件保存目录URL
String contentDisposition = ServletActionContext.getRequest().getHeader("Content-Disposition");// 如果是HTML5上传文件,那么这里有相应头的
if (contentDisposition != null) {// HTML5拖拽上传文件
Long fileSize = Long.valueOf(ServletActionContext.getRequest().getHeader("Content-Length"));// 上传的文件大小
String fileName = contentDisposition.substring(contentDisposition.lastIndexOf("filename=\""));// 文件名称
fileName = fileName.substring(fileName.indexOf("\"") + 1);
fileName = fileName.substring(0, fileName.indexOf("\""));
ServletInputStream inputStream;
try {
inputStream = ServletActionContext.getRequest().getInputStream();
} catch (IOException e) {
this.uploadError("上传文件出错!");
return;
}
if (inputStream == null) {
this.uploadError("您没有上传任何文件!");
return;
}
if (fileSize > ResourceUtil.getUploadFileMaxSize()) {
this.uploadError("上传文件超出限制大小!", fileName);
return;
}
// 检查文件扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String> asList(ResourceUtil.getUploadFileExts().split(",")).contains(fileExt)) {
this.uploadError("上传文件扩展名是不允许的扩展名。\n只允许" + ResourceUtil.getUploadFileExts() + "格式!");
return;
}
savePath += fileExt + "/";
saveUrl += fileExt + "/";
SimpleDateFormat yearDf = new SimpleDateFormat("yyyy");
SimpleDateFormat monthDf = new SimpleDateFormat("MM");
SimpleDateFormat dateDf = new SimpleDateFormat("dd");
Date date = new Date();
String ymd = yearDf.format(date) + "/" + monthDf.format(date) + "/" + dateDf.format(date) + "/";
savePath += ymd;
saveUrl += ymd;
File uploadDir = new File(savePath);// 创建要上传文件到指定的目录
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;// 新的文件名称
File uploadedFile = new File(savePath, newFileName);
try {
FileCopyUtils.copy(inputStream, new FileOutputStream(uploadedFile));
} catch (FileNotFoundException e) {
this.uploadError("上传文件出错!");
return;
} catch (IOException e) {
this.uploadError("上传文件出错!");
return;
}
this.uploadSuccess(ServletActionContext.getRequest().getContextPath() + saveUrl + newFileName, fileName, 0);// 文件上传成功
return;
}
MultiPartRequestWrapper multiPartRequest = (MultiPartRequestWrapper) ServletActionContext.getRequest();// 由于struts2上传文件时自动使用了request封装
File[] files = multiPartRequest.getFiles(ResourceUtil.getUploadFieldName());// 上传的文件集合
String[] fileNames = multiPartRequest.getFileNames(ResourceUtil.getUploadFieldName());// 上传文件名称集合
if (files == null || files.length < 1) {
this.uploadError("您没有上传任何文件!");
return;
}
for (int i = 0; i < files.length; i++) {// 循环所有文件
File file = files[i];// 上传的文件(临时文件)
String fileName = fileNames[i];// 上传文件名
if (file.length() > ResourceUtil.getUploadFileMaxSize()) {
this.uploadError("上传文件超出限制大小!", fileName);
return;
}
// 检查文件扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String> asList(ResourceUtil.getUploadFileExts().split(",")).contains(fileExt)) {
this.uploadError("上传文件扩展名是不允许的扩展名。\n只允许" + ResourceUtil.getUploadFileExts() + "格式!");
return;
}
savePath += fileExt + "/";
saveUrl += fileExt + "/";
SimpleDateFormat yearDf = new SimpleDateFormat("yyyy");
SimpleDateFormat monthDf = new SimpleDateFormat("MM");
SimpleDateFormat dateDf = new SimpleDateFormat("dd");
Date date = new Date();
String ymd = yearDf.format(date) + "/" + monthDf.format(date) + "/" + dateDf.format(date) + "/";
savePath += ymd;
saveUrl += ymd;
File uploadDir = new File(savePath);// 创建要上传文件到指定的目录
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;// 新的文件名称
File uploadedFile = new File(savePath, newFileName);
try {
FileCopyUtils.copy(file, uploadedFile);// 利用spring的文件工具上传
} catch (Exception e) {
this.uploadError("上传文件失败!", fileName);
return;
}
this.uploadSuccess(ServletActionContext.getRequest().getContextPath() + saveUrl + newFileName, fileName, i);// 文件上传成功
}
}