How to delete files of a directory but not the folders

点点圈 提交于 2019-12-01 10:40:59

Why not just do

if (!myFile.isDirectory()) myFile.delete();

instead of

myFile.delete();

?

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

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/"));

Ryan Stewart

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

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);
            }
        }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!