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 Check if a Directed Graph is a Tree or Not Using DFS
Beans and Dependency Injection
Introduction to Java 8 Streams
Retrieve User Information in Spring Security
Java Program to Find kth Smallest Element by the Method of Partitioning the Array
Tránh lỗi NullPointerException trong Java như thế nào?
Introduction to PCollections
Java Program to Perform Sorting Using B-Tree
Introduction to Spring Cloud CLI
Hướng dẫn Java Design Pattern – Builder
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
How to Count Duplicate Elements in Arraylist
Phương thức forEach() trong java 8
Java Program to Implement Sorted Singly Linked List
Format ZonedDateTime to String
Guide to Character Encoding
Java Program to Implement Sparse Array
Spring Boot Application as a Service
A Guide to Spring Cloud Netflix – Hystrix
Java Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
Java Program to Implement LinkedBlockingDeque API
Arrays.asList vs new ArrayList(Arrays.asList())
Properties with Spring and Spring Boot
Java Program to Implement LinkedHashSet API
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
Spring Boot - Building RESTful Web Services
Guide to Dynamic Tests in Junit 5
Spring WebClient Requests with Parameters
Java InputStream to Byte Array and ByteBuffer
Java – Random Long, Float, Integer and Double
Java Program to Implement Gift Wrapping Algorithm in Two Dimensions