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.
Method available in every Java versionFile filePath = new File( "SomeFileToDelete. txt" ); boolean success = filePath. delete();
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.
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.
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.
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
file.delete();
if the file doesn't exist, it will return false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With