Deletes a file if it exists and returns true.
Files#delete() throws exception if file does not exits but this method returns false in that case.
package com.logicbig.example.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class DeleteIfExistsExample {
public static void main(String... args) throws IOException {
Path path = Files.createTempFile("test-file", ".txt");
//deleting
boolean deleted = Files.deleteIfExists(path);
System.out.println("File deleted: " + deleted);
//deleting non-exiting file
boolean deletedAgain = Files.deleteIfExists(path);
System.out.println("File deleted again: " + deletedAgain);
}
}
Output
File deleted: true
File deleted again: false