Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java better way to delete file if exists

Tags:

java

We need to call file.exists() before file.delete() before we can delete a file E.g.

 File file = ...;  if (file.exists()){      file.delete();  }   

Currently in all our project we create a static method in some util class to wrap this code. Is there some other way to achieve the same , so that we not need to copy our utils file in every other project.

like image 270
Michal Chmi Avatar asked Dec 22 '14 09:12

Michal Chmi


People also ask

How do you delete a file that is used by another process in Java?

Method available in every Java versionFile filePath = new File( "SomeFileToDelete. txt" ); boolean success = filePath. delete();

How do I delete a file in Java 8?

To delete a file in Java, we can use the delete() method from Files class. We can also use the delete() method on an object which is an instance of the File class.

How do you force delete a file in Java?

To force delete file using Java, we can use the FileUtils or FileDeleteStrategy class available in Apache Commons Io. We can also use FileDeleteStrategy class of apache commons io to force delete file, even if the file represents a non-enpty directory . the delete() method deletes the file object.

How do I delete an existing file and create a new file in Java?

We use the method createNewFile() of the java. After creating this object, we call the createNewFile() method with this object. This method creates a new file in Java. Its return type is boolean. It returns true if the file is created successfully, else false if the file with the given name already exists.


2 Answers

Starting from Java 7 you can use deleteIfExists that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via toPath method . E.g.

File file = ...; boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block 
like image 57
sol4me Avatar answered Oct 12 '22 00:10

sol4me


file.delete(); 

if the file doesn't exist, it will return false.

like image 38
Martijn Courteaux Avatar answered Oct 12 '22 00:10

Martijn Courteaux