How to delete files of a directory but not the folders

后端 未结 6 2123
死守一世寂寞
死守一世寂寞 2021-01-15 12:48

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

相关标签:
6条回答
  • 2021-01-15 13:13

    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();
    }
    
    0 讨论(0)
  • 2021-01-15 13:14

    Why not just do

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

    instead of

    myFile.delete();
    

    ?

    0 讨论(0)
  • 2021-01-15 13:17

    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

    0 讨论(0)
  • 2021-01-15 13:21

    Using recursion it's very neat ;-)

    private void deleteFiles(File file) {
        if (file.isDirectory())
            for (File f : file.listFiles())
                deleteFiles(f);
        else
            file.delete();
    }
    
    0 讨论(0)
  • 2021-01-15 13:25

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

    0 讨论(0)
  • 2021-01-15 13:30

    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);
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题