English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this instance, we will learn how to use the Java File and Files classes to delete files.
import java.io.File; public static void main(String[] args) { try { //Path path = Paths.get("JavaFile.java"); File file = new File("JavaFile.java"); // boolean value = Files.deleteIfExists(path); boolean value = file.delete(); System.out.println("JavaFile.java has been successfully deleted."); else { } System.out.println("File does not exist"); catch (Exception e) { } } }
In the above example, we used the File class's delete() method to delete the file named JavaFile.java file.
Here, if the file exists, the message is displayedJavaFile.java has been successfully deleted. Otherwise, it will display “ File does not exist.
For more information about files, please visitJava File.
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public static void main(String[] args) { try { Create a file object //Path path = Paths.get("JavaFile.java"); Delete File //boolean value = Files.deleteIfExists(path); if (value) { System.out.println("JavaFile.java has been successfully deleted."); else { } System.out.println("File does not exist"); catch (Exception e) { } } e.getStackTrace(); } } }
Here, we use the deleteIfExists() method of the java.nio.file.Files class. If the file exists at the specified path, this method will delete the file.
Notejava.nio.file is a package used to handle files in Java.