Java 删除文件

删除文件

要在 Java 中删除文件,请使用 delete() 方法:

实例
  1. import java.io.File; // Import the File class
  2. public class DeleteFile {
  3. public static void main(String[] args) {
  4. File myObj = new File("filename.txt");
  5. if (myObj.delete()) {
  6. System.out.println("Deleted the file: " + myObj.getName());
  7. } else {
  8. System.out.println("Failed to delete the file.");
  9. }
  10. }
  11. }

输出将为:

Deleted the file: filename.txt

删除文件夹

也可以删除文件夹。然而,它必须是空的:

实例
  1. import java.io.File;
  2. public class DeleteFolder {
  3. public static void main(String[] args) {
  4. File myObj = new File("C:\\Users\\MyName\\Test");
  5. if (myObj.delete()) {
  6. System.out.println("Deleted the folder: " + myObj.getName());
  7. } else {
  8. System.out.println("Failed to delete the folder.");
  9. }
  10. }
  11. }

输出将为:

Deleted the folder: Test

分类导航