File

Java Delete File Example

In this example, we are going to explain how to delete a file in Java. Of course, Java offers a very convenient API to perform deletion and creation. Most of them are placed in File class. We are going to use delete() methods that delete the file or directory. If the file is deleted successfully, the methods returns true, else false. In order to delete a directory with this method, the directory has to be empty. Java deleteOnExit() and NIO deleteIfExists() methods are discussed in detail.

1. Using delete()

Here is how you can use File.delete() to delete a file.

JavaDeleteFileExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.javacodegeeks.core.file;
 
import java.io.File;
 
public class JavaDeleteFileExample {
     
    private static final String FILE_PATH = "F:\\nikos7\\Desktop\\testFile.txt";
     
    public static void main(String[] args){
         
            if( JavaDeleteFileExample.deleteFile(FILE_PATH) ){
                System.out.println("File is deleted!");
            } else {
                System.err.println("Failed to delete file.");
            }
    }
     
    public static boolean deleteFile(String filePath){
         
        File file = new File(FILE_PATH);
         
        return file.delete();
    }
}

The output of the code above when executed is presented below:

JavaDeletFileExample Output

apples-MacBook-Air:JavaDeleteFileExample bhagvan.kommadi$ javac DeleteFileExample.java
apples-MacBook-Air:JavaDeleteFileExample bhagvan.kommadi$ java DeleteFileExample
File is deleted!
apples-MacBook-Air:JavaDeleteFileExample bhagvan.kommadi$

2. Using NIO Files.delete

Java Delete File

Most of the times you need not look any further for other ways to delete a file. But there is one problem with the above method. In case of an error, it is not informative enough about the reason of the failure. As you can see, it does not through any exceptions in case of an error. NIO’s Files.delete(Path path) method offers that extremely useful feature.

Let’s see how you can use it:

JavaDeleteFileExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.javacodegeeks.core.file;
 
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
public class JavaDeleteFileExample {
     
    private static final String FILE_PATH = "F:\\nikos7\\Desktop\\testFile.txt";
     
    public static void main(String[] args){
         
        try {
            JavaDeleteFileExample.deleteFileNIO(FILE_PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
     
    public static void deleteFileNIO(String filePath) throws IOException{
        Path path = Paths.get(filePath);
        Files.delete(path);
    }
}

Now when I run this program and "F:\\nikos7\\Desktop\\testFile.txt" does not exist in my system, here is the output I get:

1
2
3
4
5
6
7
8
9
java.nio.file.NoSuchFileException: F:\nikos7\Desktop\testFile.txt
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsFileSystemProvider.implDelete(Unknown Source)
    at sun.nio.fs.AbstractFileSystemProvider.delete(Unknown Source)
    at java.nio.file.Files.delete(Unknown Source)
    at com.javacodegeeks.core.file.JavaDeleteFileExample.deleteFileNIO(JavaDeleteFileExample.java:36)
    at com.javacodegeeks.core.file.JavaDeleteFileExample.main(JavaDeleteFileExample.java:17)

So you get a very good idea of the reason your program failed. Of course, exception handling has many other advantages like error reporting, logging etc.

3. Java File.deleteOnExit() 

The deleteOnExit method of Java File is used for deleting the file or directory after the virtual machine stops. The path of the file or directory is the parameter of the deleteOnExit method.c

DeleteFileOnExitExample Java

import java.io.File;

public class DeleteFileOnExitExample {
   public static void main(String[] args) {      
      File file = null;
            
      try {
         
         file = File.createTempFile("tmp", ".txt");
         
         System.out.println("File path is "+file.getAbsolutePath());
         
         
         file.deleteOnExit();
         
         
         file = File.createTempFile("tmp", null);
         
         
         System.out.println("File path is "+file.getAbsolutePath());
         
         
         file.deleteOnExit();
         
         System.out.println("File is deleted");
      } catch(Exception exception) {
         
         exception.printStackTrace();
      }
   }
}

The output of the code above when executed is presented below:

DeleteFileOnExitExample Output

 bhagvan.kommadi$ javac DeleteFileOnExitExample.java
 bhagvan.kommadi$ java DeleteFileOnExitExample
File path is /var/folders/cr/0y892lq14qv7r24yl0gh0_dm0000gp/T/tmp6155322606838373720.txt
File path is /var/folders/cr/0y892lq14qv7r24yl0gh0_dm0000gp/T/tmp91851378978661388.tmp
File is deleted

4. NIO deleteifexists(Path p) 

The deleteIfExists method of the NIO Files class is used to delete a file if it exists in the path. The path of the file is passed as the parameter of the method.The source code for deleteIfExists Example is presented below:

DeleteFileIfExistsExample Java

import java.io.IOException; 
import java.nio.file.*; 

public class DeleteIfExistsExample
{ 
	public static void main(String[] args) 
	{ 
		try
		{ 
			Files.deleteIfExists(Paths.get("file.txt")); 
		} 
		catch(NoSuchFileException exception) 
		{ 
			System.out.println(" file or directory does not exists"); 
		} 
		catch(DirectoryNotEmptyException exception) 
		{ 
			System.out.println("Directory not empty"); 
		} 
		catch(IOException exception) 
		{ 
			System.out.println("Not valid permissions"); 
		} 
		
		System.out.println("Deletion success"); 
	} 
} 

The output of the code above when executed is presented below:

DeleteFileIfExistsExample Output

apples-MacBook-Air:JavaDeleteFileExample bhagvan.kommadi$ javac DeleteIfExistsExample.java 
apples-MacBook-Air:JavaDeleteFileExample bhagvan.kommadi$ java DeleteIfExistsExample
Deletion success

3. Download the Source Code

This was an example on how to delete a file in Java.

Download
You can download the full source code of this example here: Java Delete File Example

Last updated on Jul. 07th, 2020

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button