How to delete a file in Java
In Java, we can use the NIO Files.delete(Path)
and Files.deleteIfExists(Path)
to delete a file.
1. Delete a file with Java NIO
1.1 The Files.delete(Path)
deletes a file, returns nothing, or throws an exception if it fails.
package com.mkyong.io.file;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class DeleteFile1 {
public static void main(String[] args) {
String fileName = "/home/mkyong/app1.log";
try {
Files.delete(Paths.get(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
}
If the file doesn’t exist, it throws NoSuchFileException
.
java.nio.file.NoSuchFileException: /home/mkyong/app1.log
1.2 The Files.deleteIfExists(Path)
also delete a file, but it returns a boolean, true if file deletion success; false if the file doesn’t exist, no exception is thrown.
package com.mkyong.io.file;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class DeleteFile2 {
public static void main(String[] args) {
String fileName = "/home/mkyong/app.log";
try {
boolean result = Files.deleteIfExists(Paths.get(fileName));
if (result) {
System.out.println("File is deleted!");
} else {
System.out.println("Sorry, unable to delete the file.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. Delete a file with Java IO
2.1 For the legacy File IO java.io.*
, we can use the File.delete()
to delete a file, and it will return boolean, true if file deletion success, false otherwise.
package com.mkyong.io.file;
import java.io.File;
public class DeleteFile3 {
public static void main(String[] args) {
String fileName = "/home/mkyong/app1.log";
try {
File file = new File(fileName);
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Sorry, unable to delete the file.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.2 The File.deleteOnExit()
is a bit special, it will delete the file when the JVM terminates normally. However, there is no guarantee on the file deletion, use it with care, or avoid this method.
File file = new File(fileName);
file.deleteOnExit();
Note
The legacy File IO java.io.*
had several drawbacks, always picks Java File NIO, java.nio.*
.
Hi mkyong, this works well if the file is on my computer but if I want to delete a file that is on a shared network folder can not. And it is not for permission, because in that same folder from java I can copy files.
Only fails to eliminate. Why?
This code is not working Even for file that already exist..
Hello there,
The files we delete go to the recycle bin.
Well I want to permanently delete
how can I do that?
I don’t want it to go to the recycle bin.
use below code to delete file-
System.gc();
file.deleteOnExit();
Thank you i fixed my error 🙂
Thanks a lot
Hello sir, i can’t delete the file , the permission should be the problem. the file place on drive C , can you help me sir . thanks 🙂
This coding is working perfectly.
This code won’t work, because there is a bug in Java File.delete(). The only thing that works is when you are having an OutputStream to set him NULL and then call System.gc();.
Win 7 delete operation failed, does working?
how to delete an xml file
Hello mkyong. thanks for your time and example.
I have question that might be complicated.
I need to erase specific files, the files must begin with two numbers, have a combination of letters and number, followed with a period, and end with valid windows file extentions, lets say .XML
(example of the file:
75.asd57.grdt5.asfA4.xml)
I already have this validation^\d{2}\.([a-zA-Z0-9]+.)*[a-z]$
but the problem is the following.
I only know 2 stuff the “preffi” and the “suffix”
preffix: the two numbers.
suffix: the extention.
what i DO not know is the “core” of the name.
(using previous example.
75.asd57.grdt5.asfA4.xml
core = asd57.grdtfA.asfA4.
and I cant really know the name of the Core, or i am not sure how can i get it.)
Any suggestions?
Most probably you already solve this, but if is any help to anyone esle….
You should try to use a filter:
File dir = new File(imageDir);
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(//your validation) && name.toLowerCase().endsWith(“.xml”);
}
});
for(File file : files)
{
file.delete();
}
String file = “75.asd57.grdt5.asfA4.xml”;
String[] m = file.split(“.”);
for (String r : m) {
//test for stuff here
}
Should maybe work?
Does this work for Macs? I just tried and got the delete op is failed
Yes this should work in Mac, Just keep in mind that the file sistem is diferent.
What I mean there is no hard drive name “C:” in mac, thats exclusive for Windows.
As long as you change the path it shoudl erase the file.
Hi,
How to delete a dynamic file in Java.
For eg file name is File19072013
this file name changes based on the date.
Thanks,
Rashmi
Hi,
check this out:
for(int month = 1; month<13;month++)
{
for(int day = 1;day=10)?day:(“0″+day)+(month>=10)?day:(“0″+month)+2013);
if(file.delete()){
System.out.println(file.getName() + ” is deleted!”);
}else{
System.out.println(“Delete operation is failed.”);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
//hope works 😕
ah shit
change line 7 with below:
File file = new File(“File”+(day>=10)?day:(“0″+day)+(month>=10)?month:(“0″+month)+2013);
Hey….mkyoung i am unable to delete .xls and csv file usinf file.delete() command please guide me thrugh example if u can….thanks in advance 🙂 🙂 🙂
you could try this:
make the code exactly the same, except for this line:
File file = new File(“C:\Users\jmshunter\Documents\myexample.xls”);
Just keep in mind a few stuff
1. your path is gonna be different, depending on where is your file located,
2. make a double backslash in any ocurrence of a single backslash.
3. I used a random name (Myexample.xls) make sure to use the correct name of the file you wanna erase.
delete operation is failed? =.= why?
Hello Sir, I am new to Java, I need to delete the specific file inside the zip archive using java.
For Example I am having three files inside the zip archive(test1.txt, test2.txt, test3.txt) respectively. In this I want to delete the text2.txt file only not others.
Please provide the code for the above scenario and sent the link to my mail sir.
I Think This code is fine but before delete , close the file i.e
file.close().
So, say I am making a simple offline database for people to use that stores all the files in the program folder. They add a file to the database, and now they want to delete it. So, I have a textbox where they can type in the name of the file (without the file extension). Would I still need to put the exact location of the file, or since it is in the programs folder could I just do
File file = new file(“/”);
file.delete(file + fileName);
Would this work?
this code is not working because you didn’t used file.createNewFile without this file is not created so how can it deleted
please correct it . if i am wrong please inform me through mail
thank you
This is demonstrate how to “delete” an existing file, not create.
can i delete a system file using this program?pls reply
Yes, You can but doing so can Damage the computer. you also need to run the program as an
Administrator for this or it will say “Access Denied”