JAVA delete file or folder


1. Four basic methods for JAVA to delete files or empty folders

JAVA provides a large number of classes to operate the IO stream, and adopts the decorator mode to enhance the IO operation layer by layer. The File class not only represents a file but also a directory in JAVA. File can create, delete, and rename files and directories. However, the functions of the File class are relatively limited. The java.nio.file package has been added in JAVA 7, and new classes such as Path, Paths, and Files have been added to make up for the shortage.

delete() of the File class

The delete method of the File class is used to delete a file or directory, and returns true if the deletion is successful, or false otherwise. It cannot tell whether the file returns false because it doesn't exist, or false if deletion of the file failed ( the file is in use ).

deleteOnExit() of the File class

The deleteOnExit() method of the File class does not return any information, so that we cannot judge the status of the file (whether it is deleted), so we should avoid using this method.

delete(Path path) of the Files class

The Files class is a tool class introduced by JAVA 7 for operating files. The Files.delete method will not return any information if the file is successfully deleted. If the file does not exist, a java.nio.file.NoSuchFileException will be thrown. If the operation is deleted is a non-empty directory, a java.nio.file.DirectoryNotEmptyException will be thrown. Recommended Use

deleteIfExists(Path path) of the Files class

The Files.deleteIfExists method returns true if the file is deleted successfully, or false if the file does not exist. If the deleted directory is not empty, java.nio.file.DirectoryNotEmptyException is thrown. Recommended Use

Summarize

It can be seen from the above summary that when the traditional IO method deletes a file or folder, when the deletion fails, at most one false is returned. The specific reason for the deletion failure cannot be discovered through this false, is it because the file itself does not have a deletion failure? Or is the file being used and the delete failed? The NIO method does a better job at this point. There are specific return values ​​or exception information for deletion success or failure, which helps us to better handle exceptions in the program when deleting files or folders.

2. How to delete the entire directory or some files in the directory

When demonstrating how to delete an entire directory or some files in a directory, let us first talk about the walkFileTree method and the FileVisitor interface in Files .

Traverse files and directories with FileVistor

In the traditional JAVA IO operation, it is necessary for the program to traverse all files and subdirectories under the specified directory, and the recursive traversal is generally used. This method is not only complicated but also has low flexibility. Therefore, JAVA 7 provides the Files tool class to help us better facilitate files and subdirectories. The Files class provides the walkFileTree method to traverse files and subdirectories.
insert image description here
Both methods require FileVistor parameter, FileVisitor represents the file visitor, the first parameter Path represents the file path to start traversing, and the int parameter represents the number of layers traversed. The walkFileTree method will automatically traverse all files and subdirectories under Path. Traversing files and subdirectories will trigger the corresponding method in FileVisitor . Four methods are defined in
FileVisitor :

//访问子目录之前触发该方法
FileVisitResult postVisitDirectory(T var1, IOException var2) throws IOException;
//访问子目录后触发该方法
FileVisitResult preVisitDirectory(T var1, BasicFileAttributes var2) throws IOException;
//访问file文件时触发该方法
FileVisitResult visitFile(T var1, BasicFileAttributes var2) throws IOException;
//访问file文件失败时触发该方法
FileVisitResult visitFileFailed(T var1, IOException var2) throws IOException;

The above four methods will return a FileVisitResult object to represent the behavior after the visit. FileVisitResult defines four behaviors:

public enum FileVisitResult {
    
    
    CONTINUE, 表示继续访问
    TERMINATE, 继续访问,但是不访问该文件或者该目录的兄弟文件或目录
    SKIP_SUBTREE,继续访问,但是不再访问该文件或者该目录的子目录
    SKIP_SIBLINGS; 终止访问

    private FileVisitResult() {
    
    
    }
}

In actual programming, you can implement your own by inheriting SimpleFileVisitor文件访问器 , or rewrite the methods in the SimpleFileVisitor class to achieve your own needs.

Files.walkFileTree deletes all files in the specified folder (code demo)

The tool class provided is to delete all subdirectories or files under the specified file or directory. If only part of the file is to be deleted, override the visitFile method rule. code show as below:

/**
 * @Author: Greyfus
 * @Create: 2022-06-26 19:24
 * @Version:
 * @Description:
 */
package com.file.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class FileUtils {
    
    

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 删除指定文件夹下文件
     *
     * @param filePath
     */
    public static void deleteFolders(String filePath) {
    
    

        Path path = Paths.get(filePath);
        try {
    
    
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
    
    
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
    
    
                    Files.delete(file);
                    LOGGER.info("删除文件: {}", file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir,
                                                          IOException exc) throws IOException {
    
    
                    Files.delete(dir);
                    LOGGER.info("文件夹被删除: {}", dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

Summarize

Files provides a large number of file operation methods, which can meet most file operation scenarios. This article does not list how to delete some files or directories under the specified file. In fact, you only need to rewrite the visitFile method to write according to your own rules. If you have any questions or better comments, please leave a message.

Guess you like

Origin blog.csdn.net/qq_43600166/article/details/125835838