如何在 Java 中删除文件或目录

x33g5p2x  于2021-10-16 转载在 Java  
字(1.3k)|赞(0)|评价(0)|浏览(356)

在这篇简单而快速的文章中,您将学习如何在 Java 中删除文件或目录。 本文演示了两种删除文件的方法 -

  • 使用Java NIO的Files.delete(Path)方法删除文件
  • 使用java.io.File类的delete()方法删除文件

使用 Java NIO 的 Files.delete() 删除文件(推荐)- JDK 7+

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

public class DeleteFileExample {
    public static void main(String[] args) throws IOException {
        // File or Directory to be deleted
        Path path = Paths.get("./demo.txt");

        try {
            // Delete file or directory
            Files.delete(path);
            System.out.println("File or directory deleted successfully");
        } catch (NoSuchFileException ex) {
            System.out.printf("No such file or directory: %s\n", path);
        } catch (DirectoryNotEmptyException ex) {
            System.out.printf("Directory %s is not empty\n", path);
        } catch (IOException ex) {
            System.out.println(ex);
        }
    }
}

还有一种方法 deleteIfExists(Path) 可以删除文件,但如果文件不存在,它不会抛出异常。

// Delete file or directory if it exists
boolean isDeleted = Files.deleteIfExists(path);
if(isDeleted) {
    System.out.println("File deleted successfully");
} else {
    System.out.println("File doesn't exist");
}

使用 File.delete 方法在 Java 中删除文件 - JDK 6

您可以使用 java.io.File 类的 delete() 方法来删除文件或目录。 下面是一个例子:

import java.io.File;

public class DeleteFileExample1 {
    public static void main(String[] args) {
        // File to be deleted
        File file = new File("foo.txt");

        // Delete file
        boolean isDeleted = file.delete();

        if(isDeleted) {
            System.out.println("File deleted successfully");
        } else {
            System.out.println("File doesn't exist");
        }
    }
}

相关文章

微信公众号

最新文章

更多