boolean delete


描述

所述java.io.File.delete()方法删除由抽象路径名定义的文件或目录。要删除目录,该目录必须为空。

声明

以下是java.io.File.delete()方法的声明

public boolean delete()

参数

NA

返回值

如果成功删除文件,则此方法返回true,否则返回false。

异常

SecurityException - 如果SecurityManager.checkWrite(java.lang.String)方法拒绝对文件的删除访问

实例

以下示例显示了java.io.File.delete()方法的用法。

package com.tutorialspoint;

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      boolean bool = false;

      try {
         // create new file
         f = new File("test.txt");

         // tries to delete a non-existing file
         bool = f.delete();

         // prints
         System.out.println("File deleted: "+bool);

         // creates file in the system
         f.createNewFile();

         // createNewFile() is invoked
         System.out.println("createNewFile() method is invoked");

         // tries to delete the newly created file
         bool = f.delete();

         // print
         System.out.println("File deleted: "+bool);

      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

让我们编译并运行上面的程序,这将产生以下结果

File deleted: false
createNewFile() method is invoked
File deleted: true