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.


Advanced: Deleting a Non-Empty Directory

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.

Recursive Directory Deletion

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


Advanced: Deleting Files on JVM Exit

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.

Using `deleteOnExit()`

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


Exercise

?

What happens if you use `File.delete()` on a file that does not exist?