If you want to get rid of useless files, delete them using Java methods. Removing files and directories in Java is a straightforward process. There is a range of methods for handling the task - developers can choose the one they are most comfortable with. Here’s a short guide to get rid of unneeded Java files without breaking your code. Let’s get started.
How to delete a file in Java with java.io.File.Delete() method
You can use this method to delete a directory or a file matching the pathname you put in the brackets. Keep in mind that a directory, in order to be deleted, needs to have no file. Let’s take a look at how to delete a file in Java usingFile.Delete()
.Declaring java.io.File.Delete()
Here’s how you declare the method to get rid of an unneeded file:
// Java code for file deletion
import java.io.*;
public class Test
{
public static void main(String[] args)
{
File file = new File("C:\\Users\\Admin\\Files\\1.txt");
if(file.delete())
{
System.out.println("File deleted successfully");
}
else
{
System.out.println("Failed to delete the file");
}
}
}
If you can access the file and if it exists, you’ll get the corresponding return. In the case of failure, you’ll get a “Failed to delete the file” alert.Using java.nio.files.deleteIfExists() to remove Java files
This method helps Java developers to delete a file by specifying its path. Similarly tojava.io.FileDelete()
, the method will return true if the file was accessed and deleted successfully, and show the failure output if something went wrong.
The most common reason for java.nio.files.deleteIfExists()
failure is a wrong pathname - simply put, there’s no file with matching parameters in the directory you specified.
To get a deeper understanding if java.nio.files.deleteIfExists()
, let’s take a look at how it processes different file types:- Symbolic links - the link, not the file behind it, gets deleted.
- Directories - a directory will be deleted successfully as soon as it’s empty or has only special entries (relevant only for few specifications of the method).
- Files - in most cases, as long as the path you named in the method is the right one and you have access to the file, it will be deleted successfully. However, the specifications of some operating systems don’t allow developers to delete files that are currently open.
Declaring java.niofile.deleteIfExists
Declaring the method is straightforward - let’s take a look at its general syntax.
public static boolean deleteIfExists(Path path)
throws IOException
Parameters of java.niofile.deleteIfExists
There’s a single parameter a developer needs to specify to run the method - the path to the file he wants to remove from the system.java.niofile.deleteIfExists return
The method has two return values:- True, when the file is deleted smoothly.
- False, if there’s an error in the process (the directory is not empty, the file doesn’t exist, the developer doesn’t have needed permissions, etc).
java.niofile.deleteIfExists exceptions
As for exceptions, there are three example scenarios developers should brace themselves for:- DirectoryNotEmptyException - as the name suggests, this one means that there is a field inside your directory. Once you move them someplace else, you’ll be able to successfully complete directory deletion.
- SecurityException - if a security manager is installed on your device, a file deletion method will be overridden by
SecurityManager.checkdelete(String)
. As a result, a developer will get an exception warning. - IOException has to do with I/O errors - hard drive incompatibility, outdated driver selection, etc.
Examples of using deleteIfExists()
// Java program to show deleteIfExists() file handling
// java.nio.file.Files.deleteIfExists() method
import java.io.IOException;
import java.nio.file.*;
public class GFG {
public static void main(String[] args)
{
// create object of Path
Path path
= Paths.get("D:\\Work\\Test\\file1.txt");
// deleteIfExists File
try {
Files.deleteIfExists(path);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Example #2
/ Sample Java deletion program
// java.nio.file.Files.deleteIfExists() method
import java.io.IOException;
import java.nio.file.*;
public class GFG {
public static void main(String[] args)
{
// create an object of Path
Path pathOfFile
= Paths.get("D:\\Work\\Test\\"
+ "text1.txt");
// delete File if file exists
try {
boolean result
= Files.deleteIfExists(pathOfFile);
if (result)
System.out.println("File is deleted");
else
System.out.println("File does not exists");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Conclusion
These are the main ways to delete file in Java. Since they have the same parameters, feel free to use them interchangeably. After practicing Java file deletion a couple of times, you will definitely have the hang of it.More reading: |
---|
GO TO FULL VERSION