java - How to delete the list of files batch by batch? -
i trying delete older files in directory using below code.
for(file listfile : listfiles) { if(listfile.lastmodified() < purgetime) //checks if lastmodified time of file lesser purge time { try{ listfile.delete(); // delete file if lastmodified time lesser purge time //system.out.println("files deleted"); logger.error(new stringbuffer(contextinfo).append("files deleted")); }catch(exception e){ //system.out.println("filedeletionerror"+e.tostring()); } }else{ logger.error(new stringbuffer(contextinfo).append("files not deleted")); //system.out.println("files not deleted"); } }
the problem facing here if directory has more 2 million records, application not able process it. there way can delete them batch?
you can delete files in parallel using multithreading each thread deleting 1 file. assuming using java-8, following code should serve guide
list<file> listfiles = (list<file>) arrays.aslist(dir.listfiles()); listfiles.parallelstream().foreach((file)->{ string filename = file.getname(); if(file.lastmodified() < purgetime){ if(!file.delete()){ system.out.println("can't delete file: "+filename); }else{ system.out.println("deleted: "+filename); } } });
if want accomplish same using java-6 may use following approach:
file[] listfiles=dir.listfiles(); executorservice tpe = executors.newfixedthreadpool(10); for(file file:listfiles){ runnable r = new runnable() { @override public void run() { string filename = file.getname(); system.out.println(filename+":"+file.lastmodified()); if(file.lastmodified() < purgetime){ if(!file.delete()){ system.out.println("can't delete file: "+filename); }else{ system.out.println("deleted: "+filename); } } } }; tpe.submit(r); } tpe.shutdown();
Comments
Post a Comment