search
HomeJavajavaTutorialHow to delete files or folders in Java?

    Four basic methods to delete files or folders

    The following four methods can all delete files or folders.

    What they have in common is:

    Deletion will fail when the folder contains sub-files, which means that these four methods can only delete empty folders.

    //delete is to perform deletion immediately, while deleteOnExit is to delete the program when it exits the virtual machine.

    delete() of File class

    • deleteOnExit() of File class: When the virtual machine terminates, delete The file or directory represented by the File object. If it represents a directory, you need to ensure that the directory is empty, otherwise it cannot be deleted and there is no return value.

    • Files.delete(Path path): Delete files located on the path passed as parameter. For other file system operations, this method may not be atomic. If the file is a symbolic link, the symbolic link itself will be deleted rather than the final target of the link. If the file is a directory, this method only deletes the file if the directory is empty.

    Files.deleteIfExists(Path path)

    It should be noted that:

    The File class in traditional IO and the Path class in NIO can represent both files and folder.

    A simple comparison of the above four methods
    ## DeleteOnExit() of File classTraditional IO, this is a pitfall, avoid usingvoidIt cannot be used, but if it does not exist, the deletion will not be performedCannot (return void)Files.delete(Path path)NIO, it is recommended to use voidNoSuchFileExceptionDirectoryNotEmptyExceptionFiles.deleteIfExists(Path path)NIOtruefalseDirectoryNotEmptyException##Comparison between File.delete() and Files.delete(Path path)
    - Explanation Successful return value Whether it can be judged that the folder does not exist and causes failure Whether it can be judged that the folder is not empty and causes failure
    delete( of File class ) Traditional IO true Cannot (return false) Cannot (return false)
    //删除暂存的pdf
    File file =new File(pdfFilename);
    file.delete();
    
    Path path4 = Paths.get(pdfFilename);
    Files.delete(path4);
    Difference:

    - JDKSourceParametersReturn value##Exception declarationNo declarationStatement to throw java.io.IOExceptionThe file does not existDo not throw exception, return falseThrow java.nio. file.NoSuchFileExceptionDelete non-empty directoryCannot delete, return falseCannot delete, throw java.nio.file.DirectoryNotEmptyExceptionDelete occupied filesCannot be deleted, return falseCannot be deleted, throw java.nio.file.FileSystemExceptionThe file cannot be deleted for other reasonsDo not throw exception, return falseThrow the specific subclass of java.io.IOException
    -File.delete() Files.delete(Path path)
    JDK1.0 JDK1.7
    Instance method of java.io.File object Static method of java.nio.file.Files class
    No parameters java.nio.file.Path
    boolean void
    ##

    如何删除整个目录或者目录中的部分文件

    先造数据

    private  void createMoreFiles() throws IOException {
       Files.createDirectories(Paths.get("D:\data\test1\test2\test3\test4\test5\"));
       Files.write(Paths.get("D:\data\test1\test2\test2.log"), "hello".getBytes());
       Files.write(Paths.get("D:\data\test1\test2\test3\test3.log"), "hello".getBytes());
    }
    walkFileTree与FileVisitor

    使用walkFileTree方法遍历整个文件目录树,使用FileVisitor处理遍历出来的每一项文件或文件夹

    • FileVisitor的visitFile方法用来处理遍历结果中的“文件”,所以我们可以在这个方法里面删除文件

    • FileVisitor的postVisitDirectory方法,注意方法中的“post”表示“后去做……”的意思,所以用来文件都处理完成之后再去处理文件夹,所以使用这个方法删除文件夹就可以有效避免文件夹内容不为空的异常,因为

    在去删除文件夹之前,该文件夹里面的文件已经被删除了。

    @Test
    void testDeleteFileDir5() throws IOException {
       createMoreFiles();
       Path path = Paths.get("D:\data\test1\test2");
    
       Files.walkFileTree(path,
          new SimpleFileVisitor<Path>() {
             // 先去遍历删除文件
             @Override
             public FileVisitResult visitFile(Path file,
                                      BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                System.out.printf("文件被删除 : %s%n", file);
                return FileVisitResult.CONTINUE;
             }
             // 再去遍历删除目录
             @Override
             public FileVisitResult postVisitDirectory(Path dir,
                                             IOException exc) throws IOException {
                Files.delete(dir);
                System.out.printf("文件夹被删除: %s%n", dir);
                return FileVisitResult.CONTINUE;
             }
    
          }
       );
    
    }

    下面的输出体现了文件的删除顺序

    文件被删除 : D:\data\test1\test2\test2.log

    文件被删除 : D:\data\test1\test2\test3\test3.log

    文件夹被删除 : D:\data\test1\test2\test3\test4\test5

    文件夹被删除 : D:\data\test1\test2\test3\test4

    文件夹被删除 : D:\data\test1\test2\test3

    文件夹被删除 : D:\data\test1\test2

    我们既然可以遍历出文件夹或者文件,我们就可以在处理的过程中进行过滤。比如:

    按文件名删除文件或文件夹,参数Path里面含有文件或文件夹名称

    按文件创建时间、修改时间、文件大小等信息去删除文件,参数BasicFileAttributes 里面包含了这些文件信息。

    Files.walk

    如果你对Stream流语法不太熟悉的话,这种方法稍微难理解一点,但是说实话也非常简单。

    使用Files.walk遍历文件夹(包含子文件夹及子其文件),遍历结果是一个Stream

    对每一个遍历出来的结果进行处理,调用Files.delete就可以了。

    @Test
    void testDeleteFileDir6() throws IOException {
       createMoreFiles();
       Path path = Paths.get("D:\data\test1\test2");
    
       try (Stream<Path> walk = Files.walk(path)) {
          walk.sorted(Comparator.reverseOrder())
             .forEach(DeleteFileDir::deleteDirectoryStream);
       }
    
    }
    
    private static void deleteDirectoryStream(Path path) {
       try {
          Files.delete(path);
          System.out.printf("删除文件成功:%s%n",path.toString());
       } catch (IOException e) {
          System.err.printf("无法删除的路径 %s%n%s", path, e);
       }
    }

    问题:怎么能做到先去删除文件,再去删除文件夹?

    利用的是字符串的排序规则,从字符串排序规则上讲,“D:\data\test1\test2”一定排在“D:\data\test1\test2\test2.log”的前面。

    所以我们使用“sorted(Comparator.reverseOrder())”把Stream顺序颠倒一下,就达到了先删除文件,再删除文件夹的目的。

    下面的输出,是最终执行结果的删除顺序。

    删除文件成功:D:\data\test1\test2\test3\test4\test5

    删除文件成功:D:\data\test1\test2\test3\test4

    删除文件成功:D:\data\test1\test2\test3\test3.log

    删除文件成功:D:\data\test1\test2\test3

    删除文件成功:D:\data\test1\test2\test2.log

    删除文件成功:D:\data\test1\test2

    传统IO-递归遍历删除文件夹

    传统的通过递归去删除文件或文件夹的方法就比较经典了

    //传统IO递归删除
    @Test
    void testDeleteFileDir7() throws IOException {
       createMoreFiles();
       File file = new File("D:\data\test1\test2");
       deleteDirectoryLegacyIO(file);
    
    }
    
    private void deleteDirectoryLegacyIO(File file) {
    
       File[] list = file.listFiles();  //无法做到list多层文件夹数据
       if (list != null) {
          for (File temp : list) {     //先去递归删除子文件夹及子文件
             deleteDirectoryLegacyIO(temp);   //注意这里是递归调用
          }
       }
    
       if (file.delete()) {     //再删除自己本身的文件夹
          System.out.printf("删除成功 : %s%n", file);
       } else {
          System.err.printf("删除失败 : %s%n", file);
       }
    }

    需要注意的是:

    listFiles()方法只能列出文件夹下面的一层文件或文件夹,不能列出子文件夹及其子文件。

    先去递归删除子文件夹,再去删除文件夹自己本身。

    The above is the detailed content of How to delete files or folders in Java?. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

    Start Spring using IntelliJIDEAUltimate version...

    How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

    When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

    How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

    How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

    How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

    Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

    How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

    Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

    E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

    Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

    How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

    How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.