附录里面回加上工程代码,到时候各异直接下载下来
1)先看项目的配置文件(mergeFilleUtil.properties),log4j内容我就不贴了,一会儿自己下载看看就行:
#原始文件
PROVINCE_DIR=E:\\test\\rootfile
#解压后文件存放的路径
UN_ZIP_PATH=E:\\test\\unZip
#合并后文件存放的路径
OUT_PATH=E:\\test\\result
#已经处理过的文件存放路径
DONE_FILE_PATH=E:\\test\\doneFile
#任务执行结束后哪些文件路径下的需要删除
DELETE_PATH=E:\\test\\rootfile,E:\\test\\unZip
#配置任务的时间间隔,以秒为单位,一天是:24*60*60*1000
TASK_PERIOD=86400
#任务开始的小时时间
TASK_BEGIN_HOUR=9
#任务开始的分钟
TASK_BEGIN_MINUTE=26
2)主程序入口:
public static void main(String[] args) {
Map proMap = LoadProperty.readProperty();
Timer timer = new Timer();
MergeFileUtil mergeTask = new MergeFileUtil();//要执行的任务
//任务的时间间隔,1000表示1秒
long intevalPeriod = Long.valueOf(proMap.get("TASK_PERIOD").toString());
//Calendar类封装了一系列操作date时间的方法
Calendar calendar = Calendar.getInstance();
int year = calendar.get(calendar.YEAR);
int month = calendar.get(calendar.MONTH);
int day = calendar.get(calendar.DAY_OF_MONTH);
//指定每天执行任务的小时跟分钟比如19点32分
int hour = Integer.valueOf(proMap.get("TASK_BEGIN_HOUR").toString());
int minute = Integer.valueOf(proMap.get("TASK_BEGIN_MINUTE").toString());
calendar.set(year, month, day, hour, minute);
//Calendar.getTime()方法返回Date类型的返回值
Date date = calendar.getTime();
System.out.println("运行时间:" +year+"-"+month+"-"+day+"-"+hour+"-"+minute);
//指定定时任务的执行规则,调用定时任务。开始执行
timer.schedule(mergeTask, date, intevalPeriod*1000);
}
}
3)读取配置文件工具类:
public class LoadProperty {
private static Logger log = Logger.getLogger(LoadProperty.class);
private static Properties prop;
static{
ClassLoader loader = LoadProperty.class.getClassLoader();
InputStream in = loader.getResourceAsStream("mergeFilleUtil.properties");//此时仍然把资源装载近内存中了。
prop = new Properties();
try {
//utf-8编码配置文件,防止中文路径出错
prop.load(new InputStreamReader(in, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
log.error("加载配置文件出错,请检查!");
} catch (IOException e1) {
log.error("加载配置文件流出错,请检查!");
} finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@SuppressWarnings("rawtypes")
public static Map readProperty(){
return prop;
}
}
4) 多线程文件解压合并工具类
public class MergeFileUtil extends TimerTask{
private static Logger log = Logger.getLogger(MergeFileUtil.class);
@Override
public void run() {
unZipFile();
}
//解压
@SuppressWarnings("rawtypes")
public void unZipFile(){
//读取配置文件中的路径
Map proMap = LoadProperty.readProperty();
String rootdir = proMap.get("PROVINCE_DIR").toString();
String unZipPath = proMap.get("UN_ZIP_PATH").toString();
String outDir = proMap.get("OUT_PATH").toString();
File rootfile=new File(rootdir);
if(!rootfile.exists()||!rootfile.isDirectory()){
log.error("文件路径不存在,请检查欲解压的文件所在目录是否填写正确!");
return;
}else{
File[] files=rootfile.listFiles();
if(files.length==0){
log.error("警告:没有要解压的文件!请检查:"+rootfile+"下是否存在需解压的文件!");
}else{
//分配解压线程池
ExecutorService pool=Executors.newFixedThreadPool(files.length);