I am trying to delete all files in a folder:-
import java.io.*;
public class AddService {
public static void main(String args[]){
File folder=
There are any number of reasons why a file cannot be deleted; it may not exist, it may be a non-empty directory, you may not have closed all resources using it, and your program may not have permission to do so, to name a few.
Unfortunately the File.delete() method provides very little information as to why; it's pretty much up to you to poke around and figure it out. But there's good news; you don't want to use File
in the first place.
Java 7 introduced the new java.nio.file package which is a much more robust file access API. It provides the concept of an abstract Path and separates concrete operations into the Files class, in particular it provides Files.delete() which is documented to raise clear exceptions describing the reasons deletion might fail.
Use Path
and Files
; you'll be glad you did.
I figured it out, I was using a FileReader to read contents of the file which I didn't close. Sorry for not providing the entire code
You have not given the full path for the folder. Also note to use forward slash.
try{
File folder=new File("C:/xxxx/xxxx/xxxx/inputs");
File[] listOfFiles=folder.listFiles();
for(File file:listOfFiles){
if(file.delete())
System.out.println("File deleted");
else
System.out.println("File not deleted");
}
}
catch(Exception e)
{
System.out.println(e.printStackTrace());
}
Always use try-catch for code that contains methods which throws Exceptions.
There is nothing wrong with your code except you should give the full path.
try this : File folder=new File("C:\\inputs");
instead of this line : File folder=new File("inputs");