Java Delete Files

Java Delete Files

To delete a file in Java, you can use methods from both the traditional java.io and the modern java.nio packages.


1. Using 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.

It's good practice to first check if the file exists before attempting to delete it.

Using `File.delete()`

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."); } } }


2. Using java.nio.file.Files.delete()

The modern approach uses the Files.delete() or Files.deleteIfExists() methods from the NIO.2 API.

Using `Files.deleteIfExists()`

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()); } } }

Deleting a Directory

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.