How to delete file in Java

No nonsense, just issue the File.delete() to delete a file, it will return a boolean value to indicate the delete operation status; true if the file is deleted; false if failed.

Example

In this example, it will delete a log file named “c:\\logfile20100131.log”.


package com.mkyong.file;

import java.io.File;

public class DeleteFileExample
{
    public static void main(String[] args)
    {	
    	try{
    		
    		File file = new File("c:\\logfile20100131.log");
        	
    		if(file.delete()){
    			System.out.println(file.getName() + " is deleted!");
    		}else{
    			System.out.println("Delete operation is failed.");
    		}
    	   
    	}catch(Exception e){
    		
    		e.printStackTrace();
    		
    	}
    	
    }
}

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
20 Comment threads
10 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
26 Comment authors
PrabhakarAhmet Hüdai KayaNirmalFagnerJohn Mickel Almeñe Recent comment authors
newest oldest most voted
Christian
Guest
Christian

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?

culleen
Guest
culleen

delete operation is failed? =.= why?

Raza
Guest
Raza

This code is not working Even for file that already exist..

milan
Guest
milan

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 🙂 🙂 🙂

jmshunter
Guest
jmshunter

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.

rrathour
Guest
rrathour

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

MohammadMehdi
Guest
MohammadMehdi

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 😕

Mohammadmehdi
Guest
Mohammadmehdi

ah shit
change line 7 with below:
File file = new File(“File”+(day>=10)?day:(“0″+day)+(month>=10)?month:(“0″+month)+2013);

trackback
?Java???????

[…] ?????????????????????????????????? ?????http://www.mkyong.com/java/how-to-delete-file-in-java/ […]

bb
Guest
bb

Does this work for Macs? I just tried and got the delete op is failed

jmshunter
Guest
jmshunter

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.

Ivan Ivanovich
Guest
Ivan Ivanovich

>”exclusive for Windows”
you have exactly ten seconds to explain why you didn’t kill yourself already!

jmshunter
Guest
jmshunter

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.… Read more »

l0lkj
Guest
l0lkj

String file = “75.asd57.grdt5.asfA4.xml”;
String[] m = file.split(“.”);
for (String r : m) {
//test for stuff here
}

Should maybe work?

Gonzalo Naveira
Guest
Gonzalo Naveira

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();

}

eddy
Guest
eddy

how to delete an xml file

Diego Lottermann
Guest
Diego Lottermann

Win 7 delete operation failed, does working?

javafreak
Guest
javafreak

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();.

Titanicjohn peter
Guest
Titanicjohn peter

This coding is working perfectly.

John Mickel Almeñe
Guest
John Mickel Almeñe

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 🙂

Fagner
Guest
Fagner

Thanks a lot

Nirmal
Guest
Nirmal

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.

Ahmet Hüdai Kaya
Guest
Ahmet Hüdai Kaya

Thank you i fixed my error 🙂

Prabhakar
Guest
Prabhakar

use below code to delete file-
System.gc();
file.deleteOnExit();

rahul
Guest
rahul

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

Alan Simeon
Guest
Alan Simeon

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?

DurgaPrasad
Guest
DurgaPrasad

I Think This code is fine but before delete , close the file i.e

file.close().