Java IO & NIO Java Java API
java.nio.file.Files
public static boolean deleteIfExists(Path path) throws IOException
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.
path
true
false
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); }}
File deleted: trueFile deleted again: false