I have create some code that deletes all the files in a folder, the issue is while this is great, I want to be able to delete all the files in a directory but leave the fold
simply just use File.isDirectory()
.
just check whether it is file or directory. if it is file then delete it otherwise leave it
in your case
if (!(myFile.isDirectory()))
{
myFile.delete();
}
Why not just do
if (!myFile.isDirectory()) myFile.delete();
instead of
myFile.delete();
?
Recursion is overkill, as evidenced by the fact that a follow-up question was needed. See my answer there for a much simpler way:
Recursive deletion causing a stack overflow error
Using recursion it's very neat ;-)
private void deleteFiles(File file) {
if (file.isDirectory())
for (File f : file.listFiles())
deleteFiles(f);
else
file.delete();
}
I think this will do
public void deleteFiles(File folder) throws IOException {
List<File> files = folder.listFiles()
foreach(File file: files){
if(file.isFile()){
file.delete();
}else if(file.isDirecotry()) {
deleteFiles(file)
}
}
}
Then you need to call deleteFiles(new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/"))
;
you can use the below method.
public void deleteFiles(File folder) throws IOException {
File[] files = folder.listFiles();
for(File file: files){
if(file.isFile()){
String fileName = file.getName();
boolean del= file.delete();
System.out.println(fileName + " : got deleted ? " + del);
}else if(file.isDirectory()) {
deleteFiles(file);
}
}
}