In this article we are going see how to delete a file by using Java programming language.
Java Program to Delete a File
JavaIO is a package that contains methods to do input and output operations. It helps us with file handling in java.
Java NIO package is also another package that handle IO operations and it might seem a replacement to JavaIO but it is not. Both these packages are used separately.
Let’s see the program to understand it clearly.
- Java Program to Delete a File By Using java.io.File.delete()
- Java Program to Delete a File By Using java.nio.file.files.deleteifexists()
Method-1: Java Program to Delete a File By Using java.io.File.delete()
Methods Used:
- delete( ) – It is a Boolean method that deletes the file and then returns 1 if file is successfully deleted else returns 0.
Approach:
- Store the file path in a file object.
- Delete the file using Boolean method
delete( )
in java. - If file was deleted print “file has been deleted”, else print “Unable to delete file”.
Program:
import java.io.*; public class Main { public static void main(String[] args) { //object of File class created File fi = new File("New Folder/file.docx"); //Tries to delete the file using java.io delete() function if(fi.delete()) { System.out.println("File has been deleted"); } //Executes if file fails to delete else { System.out.println("Unable to delete file"); } } }
Output:
File has been deleted
Method-2: Java Program to Delete a File By Using java.nio.file.files.deleteifexists()
Methods Used:
- deleteIfExists(path) – It takes the path as parameter and then deletes the file.
Approach:
- We will do it by using a try catch block.
- In the try section use the
deleteIfExists( )
function with the file path as parameter. - In the catch block catch exceptions for things when the file permissions are insufficient and file not existing exception.
- Upon successful deletion print “file has been deleted”.
Program:
import java.io.*; import java.nio.file.*; public class Main { public static void main(String[] args) { try { // Put the path into the function deleteIfExists() Files.deleteIfExists(Paths.get("E:\\New folder (2)\\New folder\\file.docx")); } // Catch exception if file does not exists catch(NoSuchFileException e) { System.out.println("File does not exist"); // Catch exception if invalid permissions catch(IOException e) { System.out.println("Invalid Permissions"); } // Prints on successful deletion System.out.println("Successfully Deleted"); } }
Output:
Successfully Deleted
Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.