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.
As mentioned above, standard delete methods fail if a directory contains files or other subdirectories. To delete a non-empty directory, you must recursively delete all its contents first.
Using the modern NIO.2 API, you can achieve this by walking the file tree with Files.walkFileTree() and a SimpleFileVisitor. By deleting files as you encounter them (visitFile) and deleting the directory itself after its contents are gone (postVisitDirectory), you can safely remove the entire folder structure.
import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes;public class Main { public static void main(String[] args) { Path directory = Paths.get("my-directory"); try { // Walk the file tree and delete files/directories bottom-up Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); // Delete the file return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); // Delete the directory after its contents are gone return FileVisitResult.CONTINUE; } }); System.out.println("Directory deleted successfully."); } catch (IOException e) { System.err.println("Error deleting directory: " + e.getMessage()); } } }
If you are working with temporary files that only need to exist while your application is running, you can register them to be automatically deleted when the Java Virtual Machine (JVM) terminates. This is done using the deleteOnExit() method.
import java.io.File; import java.io.IOException;public class Main { public static void main(String[] args) { try { File tempFile = File.createTempFile("app-log-", ".tmp"); System.out.println("Temp file created at: " + tempFile.getAbsolutePath()); // Tell the JVM to delete this file when the program exits tempFile.deleteOnExit(); System.out.println("Doing some work... file will be deleted automatically later."); } catch (IOException e) { e.printStackTrace(); } } }
What happens if you use `File.delete()` on a file that does not exist?