Picture this: you need to develop a Java application that requires you to delete one or more files.
But, of course, you only want to delete those files if they exist.
So in the olden days, you probably did an if check with the exists() method to first determine if the file existed. And, if it did exist, then you deleted it.
But what if I told you that you don't need to do it that way with Java NIO?
And I am telling you that because it's true.
Let me show you an example.
Let's say I've got a simple text file in the c:\home directory called file.txt.
Here's some code I can write to delete it:
final Path file = Paths.get("C:/", "home", "file.txt"); Files.delete(file);
That will work just fine the first time I run the code. But if I run it again I'll get NoSuchFileException.
Cuz at that point the file is already deleted.
Now as I mentioned in the intro, I could check for the file's existence ahead of time. But I don't need to.
Instead, I can use the deleteIfExists() method. It works like this:
final Path file = Paths.get("C:/", "home", "file.txt"); System.err.println(Files.deleteIfExists(file));
If the file exists, running that code will delete the file and print true.
If the file does not exist, running the code will just print false.
But it won't throw an exception if the file doesn't exist.
So deleteIfExists() is a great way to kill a couple of birds with a single stone.
Keep in mind, deleteIfExists() is meant for files. Not directories.
Yes, you can use it for directories. But the directories had better be empty. Or it won't work.
So I'd stick with using it for files only.
If you need to determine if the Path object is a file or directory, you can check out my guide on that subject.
Also, if the file or directory is a sym link, deleteIfExists() will just delete the sym link. It won't follow the sym link and delete whatever is on the other side.
Wrapping It Up
That wasn't so bad, was it?
No you can write code that's a little more concise when it comes to deleting files.
Photo by from