Javatpoint Logo
Javatpoint Logo

How to delete a file in Java

There are two methods to delete a file in Java:

  • Using File.delete() method
  • Using File.deleteOnExit() method

Java File.delete() method

In Java, we can delete a file by using the File.delete() method of File class. The delete() method deletes the file or directory denoted by the abstract pathname. If the pathname is a directory, that directory must be empty to delete. The method signature is:

The method returns true if the file or directory deleted successfully, otherwise returns false.

Example

Output:

When the file exist.

How to delete a file in Java

When the file does not exist.

How to delete a file in Java

Java File.deleteOnExit() method

The File.deleteOnExit() method also deletes the file or directory defined by abstract pathname. The deleteOnExit() method deletes file in reverse order. It deletes the file when JVM terminates. It does not return any value. Once the request has been made, it is not possible to cancel the request. So this method should be used with care.

The method signature is:

Usually, we use this method when we want to delete the temporary file. A temporary file is used to store the less important and temporary data, which should always be deleted when JVM terminates.

If we want to delete the .temp file manually, we can use File.delete() method.

Example

The following example creates a temporary file named abc.temp and delete it when the program is terminated.

Output:

How to delete a file in Java

Let's see another example that deletes text file.

Example

Output:

How to delete a file in Java
Next TopicJava Tutorial




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA