Delete a file

This example will demonstrate how to delete a file using java, java 7 NIO and apache commons. In the set up we will create a file for each of the snippets to delete.

Setup

private static final String SOURCE = "com/levelup/java/io/file-to-delete.txt";
                                        
private static final String DEST = "output/FileToDelete.txt";

@Before
public void setUp () throws IOException, URISyntaxException {

    // copy file over to delete
    Path source = Paths.get(this.getClass().getClassLoader().getResource(SOURCE).toURI());
    Path destination = Paths.get(DEST);
    
    // could of used Files.create
    java.nio.file.Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
}

Straight up Java

Using File.delete will delete a file or directory by the path defined. In the instance the directory is not empty it won't be deleted. The file.delete() will return a boolean value to indicate if the delete operation was successful. True if the file was deleted, false if it was not. You could also check if the file exists by calling fileToDelete.exists().

File.delete

@Test
public void delete_file_java_legacy () {
    
    File fileToDelete = new File(DEST);
    
    boolean hasBeenDeleted = fileToDelete.delete();
    
    assertFalse(hasBeenDeleted);
}

Java 7 File I/O

This snippet will show how to delete a file using java 7 NIO and Files utility method. We will first use Paths to obtain a reference to the location of the file and pass it to the Files.delete method. A key difference between this method and the File.delete above is that it will not return if it was successful. Be aware that on certain file systems the file must be closed to delete it.

@Test
public void delete_file_java_nio () throws IOException {
    
    Path path = Paths.get(DEST);
    
    java.nio.file.Files.delete(path);
    
    assertTrue(Files.notExists(path));
}

Apache Commons

Using apache commons we will call FileUtils.deleteQuietly to delete a file in java. This approach will not throw an exception and if it is a directory it will be delete with all of it's sub directories.

@Test
public void delete_file_java_apache () {

    Path path = Paths.get(DEST);

    FileUtils.deleteQuietly(path.toFile());
    
    assertTrue(Files.notExists(path));
}