首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

定时剔除临时文件

2012-06-30 
定时删除临时文件public class TimerDeleteFilesTask implements ITask{private ListFileInfo filespub

定时删除临时文件

public class TimerDeleteFilesTask implements ITask{private List<FileInfo> files;public class FileInfo{private String folderPath;private String regexpFileName;private boolean isRecursive;/** * 删除目录及目录下的文件 *  * @param folderPath - 文件路径 * @param regexpFileName - 匹配的后缀名称 * @param isRecursive - 是否递归删除 */public FileInfo(String folderPath, String regexpFileName, boolean isRecursive){this.folderPath = folderPath;this.regexpFileName = regexpFileName;this.isRecursive = isRecursive;}}/** * 构造方法 *  * @throws IOException */public TimerDeleteFilesTask() throws IOException{this.files = new ArrayList<FileInfo>();String tempPath = Config.getInstance().getLogDownloadTempPath();this.files.add(new FileInfo(tempPath, ".*.xls", true));}/** * 任务执行之前 */public boolean beforeExecute(){return true;}/** * 执行任务 */public void execute(){for ( FileInfo fileInfo : files ){// 判断是否是递归删除if ( fileInfo.isRecursive ){recureDeleteFile(new File(fileInfo.folderPath), fileInfo.regexpFileName);}else{deleteFiles(fileInfo.folderPath, fileInfo.regexpFileName);}}}/** * 任务执行之后 */public void afterExecute(){}/** * 查找某目录下指定扩展名的文件 *  * @param folderPath - 查找的目录路径 * @param regexpFileName-匹配文件后缀名的正则 */private void deleteFiles(String folderPath, final String regexpFileName){File[] files = new File(folderPath).listFiles();for ( int i = 0; i < files.length; ++i ){File file = files[i];if ( file.isFile() ){try{Pattern p = Pattern.compile(regexpFileName);Matcher m = p.matcher(regexpFileName);if ( m.find() ){file.delete();}}catch ( Exception e ){e.printStackTrace();}}}}/** * 递归删除路径下的指定后缀名的文件及文件夹 *  * @param path-文件路径 * @param regexpFileName-匹配文件后缀名的正则 */private void recureDeleteFile(File folder, String regexpFileName){File[] files = folder.listFiles();if (null == files){return;}for ( File file : files ){// 判断是文件还是目录,如果是文件直接删除,如果是目录再调用本身方法递归删除if ( file.isFile() ){try{Pattern p = Pattern.compile(regexpFileName);Matcher m = p.matcher(regexpFileName);if ( m.find() ){file.delete();}}catch ( Exception e ){e.printStackTrace();}}else{recureDeleteFile(file, regexpFileName);}}}@Overridepublic Priority getPriority(){return Priority.LOW;}}

热点排行