In the company project, due to do a QR code scanning platform project, is expected to produce a daily two-dimensional code image to more than 10 g, so to do a scheduled cleanup task to regularly clean up the picture, according to different scenes to keep the picture, the rule is: 1, two-dimensional code unified login image for several hours effective 2, Electronic Business card QR code days ago, These parameters are configurable.
At first, directly with the IO file operation, recursively delete the file, according to the scene to determine the deletion logic. However, after the stress test, it is found that deleting the more than 10 g file takes 20 minutes, but the test is straightforward. Cause analysis: In all the 5 levels of the directory, to traverse the matching conditions of the file, will not comply with the deletion of files, delete and use recursion, all of a three-layer loop, so that the direct traversal of data is too large, the performance of a direct decline, and later on the Internet to see a quick way to traverse, is filevisitor, so , I looked at the API of the interface, and finally wrote down, in the process, encountered a lot of pits.
First of all, to understand the next filevisitor there are four methods, the representative is to access the file's four states: Before accessing the directory, access to the directory, access to the file, when access to the file failed, this is a method can be returned: CONTINUE continue, Skip_siblings: Continue traversal, But all sibling nodes that ignore the current node return directly to the previous layer to continue traversal, Skip_subtree: Continue traversal, but ignore subdirectories, but sub-files are still accessible; TERMINATE: terminates traversal.
Operation mechanism: First according to the file directory to determine which file directory to go, the first program to run to previsitdirectory this method inside, according to their own design logic to go to different paths, where you can set your own to go to the current directory, do not go down the next level of directory, directly ignore the sub-directory, or terminate the traversal, the method is mainly to determine the traversal of the file directory. Then the program went through this method, and then run to this method: Postvisitdirectory this is mainly to traverse the current file directory when traversing to the file, ran into the visitfile inside, visitfile mainly to get the file directory under the current file, and then delete the file, After the deletion, Postvisitdirectory will change the file directory to delete. And then in turn ...
Define a class, inherit filevisitor this interface, the following main is to inherit this interface and then rewrite four methods
@Override
Public Filevisitresult previsitdirectory (Object dir,
Basicfileattributes attrs) throws IOException {
TODO auto-generated Method Stub
return null;
}
@Override
Public Filevisitresult visitfile (Object file, Basicfileattributes attrs)
Throws IOException {
TODO auto-generated Method Stub
return null;
}
@Override
Public Filevisitresult visitfilefailed (Object file, IOException exc)
Throws IOException {
TODO auto-generated Method Stub
return null;
}
@Override
Public Filevisitresult postvisitdirectory (Object dir, IOException exc)
Throws IOException {
TODO auto-generated Method Stub
return null;
}
Delete the specific implementation of the file, this is a demo version of the local test PS: The code is a bit messy, too late to tidy up.
Package com.tony.test;
Import Java.io.File;
Import java.io.IOException;
Import java.nio.file.FileVisitOption;
Import Java.nio.file.FileVisitResult;
Import Java.nio.file.FileVisitor;
Import Java.nio.file.Files;
Import Java.nio.file.Path;
Import java.nio.file.Paths;
Import java.nio.file.attribute.BasicFileAttributes;
Import Java.text.SimpleDateFormat;
Import Java.util.Calendar;
Import Java.util.Date;
Import Java.util.EnumSet;
public class DeleteFile implements Filevisitor {
private static DeleteFile Deletefileinstace;
public static DeleteFile getinstance () {
if (Deletefileinstace = = null) {
Synchronized (Deletefile.class) {
if (Deletefileinstace = = null) {
Deletefileinstace = new DeleteFile ();
}
}
}
return deletefileinstace;
}
@Override
Public Filevisitresult previsitdirectory (Object dir,
Basicfileattributes attrs) throws IOException {
String f=dir.tostring ();
if (!deletebydaysouttime (0, (Path) dir))
{
System.out.println ("Previsitdirectory F: By day Delete jumped in" +f);
return filevisitresult.skip_subtree;
}
else if (!deletebyhoursouttime (3, (Path) dir)//delete by hour
{
System.out.println ("Previsitdirectory F: Delete by the hour jumped in" +f);
return filevisitresult.skip_subtree;
}
return filevisitresult.continue;
}
@Override
Public Filevisitresult visitfile (Object file, Basicfileattributes attrs)
Throws IOException {
Boolean success = Deletefilebyfile ((Path) file);
return filevisitresult.continue;
}
@Override
Public Filevisitresult visitfilefailed (Object file, IOException exc)
Throws IOException {
return filevisitresult.continue;
}
@Override
Public Filevisitresult postvisitdirectory (Object file, IOException exc)
Throws IOException {
Boolean success=false;
/*system.out.println ("postvisitdirectory where you are F" +file.tostring ()); * *
if (exc = = null) {
/*file.separator*/
String f=file.tostring ();
Path path= (path) file;
StringBuilder stringbuilder=new StringBuilder ();
Stringbuilder.append ("E:"). Append (File.separator)
. Append ("Home"). Append (File.separator). Append ("QR"). Append (File.separator)
. Append ("1");
System.out.println ("File path" +stringbuilder.tostring ());
Delete by day
if (Deletebydaysouttime (0, (Path) file) &&!f.equals (stringbuilder.tostring ()))
{
System.out.println ("Path Count:" +path.getnamecount ());
System.out.println ("Postvisitdirectory Lao Zi jumped into the pit F" +file.tostring ());
Success = Deletefilebyfile ((Path) file);
if (success) {
System.out.println ("dir Deleted:" + (Path) file);
} else {
System.out.println ("Dir not deleted:" + (Path) file);
}
}else if (Deletebyhoursouttime (2, (Path) file) &&!f.equals ("e:\\home\\qr\\1\\20171209\\")//delete by 1 scenes per hour
{
Success = Deletefilebyfile ((Path) file);
if (success) {
System.out.println ("dir Deleted:" + (Path) file);
} else {
System.out.println ("Dir not deleted:" + (Path) file);
}
}
} else {
Throw exc;
}
return filevisitresult.continue;
}
Privateboolean deletefilebyfile (Path file) {
Boolean flag=false;
try {
flag= files.deleteifexists (file);
} catch (Exception e) {
Todo:handle exception
}
return flag;
}
/**
*
* Deleted by days, delete folder before day
*
* @param days
*/
Private Boolean deletebydaysouttime (int days, Path file) {
Boolean flag = true;
String rootpathstring= "e:\\home\\qr\\2\\";
for (int i=0;i<=days;i++) {
String getfilenamebydays=getdays (i);
if (file.tostring (). Equals (Rootpathstring+getfilenamebydays)) {//Do not delete
Flag = false;
System.out.println ("Do not delete the file directory:" +file);
}
}
return flag;
}
Private Boolean deletebyhoursouttime (int hours, Path file) {
Boolean flag = true;
String rootpathstring= "e:\\home\\qr\\1\\20171209\\";
for (int i=0;i<=hours;i++) {
String getfilenamebyhours=gethours (i);
/*system.out.println ("Currently traversed file:" +file.getfilename ());
System.out.println ("self-calculated filename" +getfilenamebyhours); */
if (file.tostring (). Equals (Rootpathstring+getfilenamebyhours)) {//Do not delete
Flag = false;
}
}
return flag;
}
/**
* Get a few days before the current time
* @param days
* @return Returns the file name of the YYYYMMDD time format
*/
Private String getDays (int days) {
Calendar calendar=calendar.getinstance ();
Calendar.add (Calendar.day_of_month,-days);
SimpleDateFormat sformat=new SimpleDateFormat ("YyyyMMdd");
Return Sformat.format (Calendar.gettime ());
}
/**
* Get the first few hours of the current time
* @param days
* @return Returns the file name of the YYYYMMDD time format
*/
Private String getHours (int hours) {
Calendar calendar=calendar.getinstance ();
Calendar.add (Calendar.hour,-hours);
SimpleDateFormat sformat=new SimpleDateFormat ("HH");
Return Sformat.format (Calendar.gettime ());
}
public static void Main (string[] args) {
/*system.out.println (Deletefileinstace.getinstance (). GetDays (1)); * *
System.out.println ("Delete by Hour");
Long start = System.currenttimemillis ();
int scence=1;
Path Directory=null;
Deletefileinstace=deletefileinstace.getinstance ();
StringBuilder sbbuilder=new StringBuilder ();
Scenario 1
Delete the folder that you thought today
if (scence>0)
{
Sbbuilder.append ("E:\\home\\qr\\1"). Append (File.separator). Append (getinstance (). GetDays (0));
Directory = Paths.get (sbbuilder.tostring ());
System.out.println (Sbbuilder.tostring ());
Enumset opts1 = Enumset.of (filevisitoption.follow_links);
try {
Files.walkfiletree (Directory, Opts1, Integer.max_value, deletefileinstace);
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}else if (scence>0)
{
Sbbuilder=new StringBuilder ();
Sbbuilder.append ("e:\\home\\qr\\2");
Directory = Paths.get (sbbuilder.tostring ());
Enumset opts3 = Enumset.of (filevisitoption.follow_links);
try {
Files.walkfiletree (Directory, OPTS3, Integer.max_value, deletefileinstace);
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
System.out.println (System.currenttimemillis ()-start);
}
}
Java NIO Filevisitor efficiently Delete files