How to delete a file in Java

Files.delete() method

The delete() method of the Files class in Java is a static method that deletes a file if it exists. Otherwise, it throws NoSuchFileException. This method can also delete a directory, but the directory’s contents should be empty.

Syntax

public static void delete(Path path)

Parameters

Path path: the path of the file to be deleted.

Return value

This method does not return anything.

Code

In the code below, we create a file using the createNewFile() method and delete the created file using the Files.delete() method.

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 Main {
public static void main(String[] args){
String f_path = "file.txt";
File file = new File("./" + f_path);
try {
System.out.println("File created - " + file.createNewFile());
Thread.sleep(10000);
Path filePath = Paths.get(f_path);
Files.delete(filePath);
System.out.println("File deleted");
} catch (IOException | InterruptedException ioException) {
ioException.printStackTrace();
}
}
}

Free Resources