Вы находитесь на странице: 1из 8

JAVA CODE FOR

DELETING FILES
AUTOMATICALLY
CREATE A SINGLE CALENDAR AT
THE BEGINNING
longcutoff=System.currentTimeMillis()-(30
*24*60*60*1000);

Subtract 30 days, and convert this to a Date


and then a long, to represent the cutoff
timestamp. Then just delete all files older
than that timestamp, comparing longs using
< or >.
CODE FOR DELETING FILE
publicstaticvoiddeleteFilesOlderThanNdays(intdaysBack,StringdirWay,org.apache.c
ommons.logging.Loglog){

Filedirectory=newFile(dirWay);
if(directory.exists()){

File[]listFiles=directory.listFiles();
longpurgeTime=System.currentTimeMillis()-(daysBack*24*60*60*1000);
for(FilelistFile:listFiles){
if(listFile.lastModified()<purgeTime){
if(!listFile.delete()){
System.err.println("Unabletodeletefile:"+listFile);
}
}
}
}else{
log.warn("Fileswerenotdeleted,directory"+dirWay+"does'ntexist!");
}
}
CALENDAR OBJECT
Calendarcal=Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH,daysBack*
-1);
longpurgeTime=cal.getTimeInMillis();
It is worthwhile printing out30 * 24 * 60 * 60
* 1000, which is anint. It will probably give
an overflow error and print a negative value.
You can correct that by changing it to30L *
24 * 60 * 60 * 1000.
publicstaticbooleanfileMove(Filef1,Filef2,booleanoverwrite){
ReadableByteChannelsrc=null;
WritableByteChanneldest=null;
booleansuccess=false;

//iff1doesnotexist,simplyreturnfalse
if(!f1.exists()){
returnfalse;
}

//DONOTOVERWRITEbyindicated!!
if(!overwrite&&f2.exists()){
returnfalse;
}

//makesurebufferempty,readyforfilling
buffer.clear();

}

}catch(Exceptionioex){
ioex.printStackTrace();
}finally{
//alwayscleanup
try{
src.close();
}catch(Exceptionex){
System.out.println("src.close()exception="+ex.getMessage());
}
try{
dest.close();
}catch(Exceptionex){
System.out
.println("dest.close()exception="+ex.getMessage());
}


}
//makesurethingswentok.
success=f2.exists();
success=success&&(f2.length()==f1.length());
System.out.println("f1.exists()="+f1.exists());//Thisvalueistrue,
try{
success=success&&f1.delete();
System.out.println("f1.delete()="+f1.delete());
}catch(Exceptione){
System.out.println("ExceptioninfileUtils:"+e.getMessage());
}
success=success&&(!f1.exists());
returnsuccess;
}

Вам также может понравиться