In this post, we will learn to delete a file from java code.
When you are delete a file from java. It will delete the file permanently. It will not moved to Trash or Recycle bin
Before executing this code, please make sure you have delete permission for that file from java.
Else you will get Permission denied Exception
Syntax
boolean isDeleted = file.delete();
Example
import java.io.File;
public class DeleteFileExample {
public static void main(String[] args) {
try {
File file = new File("C:\\sample.txt");
// Below if condition will check that file exists or not
if (file.exists()) {
boolean isDeleted = file.delete();
if (isDeleted == true) {
System.out.println("File deleted Successfully");
} else {
System.out.println("Not able to delete the file");
}
} else {
System.err.println("File path is not correct");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
File deleted Successfully
File delete using nio pacakage
In Above example, we can customize our exceptions like file not found, file delete staus.
Below example is quick way of deleting file, But we cannot customize out exception
Syntax
Files.deleteIfExists(Paths.get("C://temp//sample.txt"));
Example
import java.nio.file.Files;
import java.nio.file.Paths;
public class DeleteFileExample {
public static void main(String[] args) {
try {
// Below line will delete if the file exist
Files.deleteIfExists(Paths.get("C://temp//sample.txt"));
System.out.println("File deleted successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
File deleted successfully
Github
Related Articles
how to list all files inside a folder using java
how to read a file from java with example