Java IO & NIO - Files.deleteIfExists() Examples

Code Snippets Java IO & NIO Java 


Class:

java.nio.file.Files

java.lang.Objectjava.lang.Objectjava.nio.file.Filesjava.nio.file.FilesLogicBig

Method:

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.

Parameters:
path - the path to the file to delete
Returns:
true if the file was deleted by this method; false if the file could not be deleted because it did not exist


Examples


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




See Also