# 如何在 Java 中删除文件 - `delete()`方法

> 原文： [https://beginnersbook.com/2014/01/how-to-delete-file-in-java-delete-method/](https://beginnersbook.com/2014/01/how-to-delete-file-in-java-delete-method/)

在本教程中，我们将看到**如何在 java** 中删除文件。我们将使用`delete()`方法删除文件。

```java
public boolean delete()
```

如果指定的`File`成功删除，则此方法返回`true`，否则返回`false`。

**这是完整的代码：**

```java
import java.io.File;
public class DeleteFileJavaDemo
{
   public static void main(String[] args)
   {	
      try{
         //Specify the file name and path
    	 File file = new File("C:\\myfile.txt");
         /*the delete() method returns true if the file is
          * deleted successfully else it returns false
          */
    	 if(file.delete()){
    	    System.out.println(file.getName() + " is deleted!");
         }else{
    	    System.out.println("Delete failed: File didn't delete");
    	  }
       }catch(Exception e){
           System.out.println("Exception occurred");
    	   e.printStackTrace();
    	}
    }
}
```

输出：

```java
myfile.txt is deleted!
```

**参考：**

[`delete()` - Javadoc](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#delete())