To delete a file in Java, you can use methods from both the traditional java.io and the modern java.nio packages.
java.io.File.delete()The delete() method of the java.io.File class is the classic way to delete a file or an empty directory.
true if the file was successfully deleted.false if the file could not be deleted (e.g., the file doesn't exist, or you don't have permission).It's good practice to first check if the file exists before attempting to delete it.
import java.io.File;public class Main { public static void main(String[] args) { File myObj = new File("filename.txt"); if (myObj.delete()) { System.out.println("Deleted the file: " + myObj.getName()); } else { System.out.println("Failed to delete the file."); } } }
java.nio.file.Files.delete()The modern approach uses the Files.delete() or Files.deleteIfExists() methods from the NIO.2 API.
Files.delete(path): Deletes a file. It throws a NoSuchFileException if the file does not exist, which can be more explicit and useful for error handling.Files.deleteIfExists(path): Deletes a file if it exists. It returns true if the file was deleted, and false if the file did not exist. It does not throw an exception if the file is missing.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) { Path path = Paths.get("filename.txt"); try { if (Files.deleteIfExists(path)) { System.out.println("File deleted successfully."); } else { System.out.println("File did not exist, so it was not deleted."); } } catch (IOException e) { System.err.println("Error deleting file: " + e.getMessage()); } } }
You can use the same methods to delete a directory. However, a directory must be empty before it can be deleted. If you try to delete a non-empty directory, the operation will fail.