Java – Delete a File

1. With Java – JDK 6

Let’s start with the standard Java 6 solution:

@Test
public void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException {
    new File("src/test/resources/fileToDelete_jdk6.txt").createNewFile();

    File fileToDelete = new File("src/test/resources/fileToDelete_jdk6.txt");
    boolean success = fileToDelete.delete();

    assertTrue(success);
}

As you can see – the file must exist before the delete operation; if it doesn’t, the API will not throw any exceptions but will instead return false.

2. With Java – JDK 7

Let’s move on to the JDK 7 solution:

@Test
public void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
    Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt"));

    Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt");
    Files.delete(fileToDeletePath);
}

Now – this will make better use of exceptions. If the file doesn’t exist when the delete operation is triggered – an NoSuchFileException will be thrown by the API:

java.nio.file.NoSuchFileException: srctestresourcesfileToDelete_jdk7.txt
    at s.n.f.WindowsException.translateToIOException(WindowsException.java:79)

3. With Commons IO

Commons IO allows us to control the exceptions behavior when deleting a File. For a quiet delete that swallows any possible exceptions:

@Test
public void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException {
    FileUtils.touch(new File("src/test/resources/fileToDelete_commonsIo.txt"));
    File fileToDelete = FileUtils.getFile("src/test/resources/fileToDelete_commonsIo.txt");
    boolean success = FileUtils.deleteQuietly(fileToDelete);

    assertTrue(success);
}

Note that we can still determine if the operation was successful or not by simply checking the return value of the delete method.

Now – if we do want an exception to be thrown:

@Test
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
    FileUtils.touch(new File("src/test/resources/fileToDelete.txt"));

    FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt"));
}

If the file to be deleted doesn’t exist on the filesystem, the API will throw a standard FileNotFoundException:

java.io.FileNotFoundException: File does not exist: srctestresourcesfileToDelete.txt
    at org.apache.commons.io.FileUtils.forceDelete(FileUtils.java:2275)

And there you have it – 4 simple ways to delete a File in Java.

Related posts:

Java Program to Implement Binary Search Tree
Java Program to Implement Hash Tables Chaining with Binary Trees
Java InputStream to String
Java Program to Implement AVL Tree
Send email with JavaMail
Hướng dẫn Java Design Pattern – MVC
Java Program to Implement Graph Structured Stack
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Refactoring Design Pattern với tính năng mới trong Java 8
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
Spring Cloud AWS – EC2
How to Find an Element in a List with Java
Từ khóa static và final trong java
Spring Boot - Code Structure
Java Program to Check whether Directed Graph is Connected using DFS
Guide To CompletableFuture
Ignore Null Fields with Jackson
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Java Program to Implement Ternary Heap
Java – Get Random Item/Element From a List
Introduction to Spring Cloud Stream
Java Program to Create a Balanced Binary Tree of the Incoming Data
Java Program to Perform the Unique Factorization of a Given Number
Setting the Java Version in Maven
Spring Security Logout
Using the Not Operator in If Conditions in Java
Guide to BufferedReader
Changing Annotation Parameters At Runtime
Java Program to Check whether Graph is a Bipartite using BFS
Java Program to Perform Polygon Containment Test
Spring 5 Testing with @EnabledIf Annotation