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:

Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
Java Program to find the maximum subarray sum using Binary Search approach
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Java Program to implement Bi Directional Map
Java Convenience Factory Methods for Collections
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Hướng dẫn Java Design Pattern – Singleton
Using a List of Values in a JdbcTemplate IN Clause
Java Program to Implement LinkedList API
Check If a File or Directory Exists in Java
Java Program to Generate Random Hexadecimal Byte
Lớp Arrarys trong Java (Arrays Utility Class)
Java Program to Perform Inorder Recursive Traversal of a Given Binary Tree
Java Program to Implement Heap
Generating Random Numbers in a Range in Java
Wiring in Spring: @Autowired, @Resource and @Inject
Custom Thread Pools In Java 8 Parallel Streams
A Guide to JUnit 5
REST Pagination in Spring
Inheritance and Composition (Is-a vs Has-a relationship) in Java
Merging Two Maps with Java 8
Debug a HttpURLConnection problem
The Java 8 Stream API Tutorial
Transaction Propagation and Isolation in Spring @Transactional
Exploring the Spring 5 WebFlux URL Matching
A Guide To UDP In Java
Java Program to Implement Leftist Heap
Java Program to Check the Connectivity of Graph Using DFS
Một số nguyên tắc, định luật trong lập trình
Testing an OAuth Secured API with Spring MVC
Converting String to Stream of chars