目录

boolean delete()

描述 (Description)

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

声明 (Declaration)

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

public boolean delete()

参数 (Parameters)

NA

返回值 (Return Value)

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

异常 (Exception)

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

例子 (Example)

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

package com.iowiki;
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
↑回到顶部↑
WIKI教程 @2018