在这篇简单而快速的文章中,您将学习如何在 Java 中删除文件或目录。 本文演示了两种删除文件的方法 -
java.io.File
类的delete()方法删除文件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");
}
您可以使用 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");
}
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.callicoder.com/java-delete-file/
内容来源于网络,如有侵权,请联系作者删除!