In this example, I show you how to delete a file in Java using Files.deleteIfExists() API.
Files.deleteIfExists(Path path) API
This method deletes a file if it exists.
Java Files.deleteIfExists() API Example
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaDeleteFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/sample1.txt");
boolean fileDeleted = Files.deleteIfExists(myPath);
if (fileDeleted) {
System.out.println("File deleted");
} else {
System.out.println("File does not exist");
}
}
}
Output:
File deleted
The above example deletes a file from location "src/sample1.txt".
The Files.deleteIfExists() deletes a file and returns true if the file was deleted and false if the file could not be deleted because it did not exist.
boolean fileDeleted = Files.deleteIfExists(myPath);
Reference
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course