Home >Java >javaTutorial >How to delete files or folders in Java?

How to delete files or folders in Java?

王林
王林forward
2023-04-19 14:46:132922browse

    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:yisu.com. If there is any infringement, please contact admin@php.cn delete