Three ways to delete files or directories in java

1. Tools used

Traditional deletion uses IO streams, but this paper uses NIO streams to implement.

Two, several common methods

1. Traditional IO flow

The code is as follows (example):

//调用
 File file = new File("E:/河南省乡镇点/GIS/");
 deleteFile(file);
//删除文件夹及其文件
    public static void deleteFile(File file){
    
    
        //获取目录下子文件
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
    
    
            //打印文件名
            System.out.println("文件名:" + f.getName());
            //文件删除
            f.delete();
        }
        boolean delete = file.delete();
        System.out.println(delete);
    }

2. Forced deletion (if one deletion fails, you can perform multiple forced deletions)

The code is as follows (example):

//调用
 File file = new File("E:/河南省乡镇点/GIS/");
 forceDelete(file);
//强制删除
    public static boolean forceDelete(File file) {
    
    
        boolean result = file.delete();
        int tryCount = 0;
        while (!result && tryCount++ < 10) {
    
    
            System.gc(); //回收资源
            result = file.delete();
        }
        return result;
    }

3. Leverage NIO streams

The code is as follows (example):

 Path path= Paths.get("E:\\河南省乡镇点\\GIS");
        Files.walkFileTree(path,new SimpleFileVisitor<>(){
    
    
            //遍历删除文件
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    
    
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }
            //遍历删除目录
            public FileVisitResult postVisitDirectory(Path dir,IOException exc) throws IOException{
    
    
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });

Summarize

The benefits of using NIO stream:
1. If the deletion fails, the specific reason for the error can be given;
2. There are not many codes and high efficiency.

Guess you like

Origin blog.csdn.net/qq_37967853/article/details/127566155