如何使用默认的java包删除文件夹中的所有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22031751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:10:44  来源:igfitidea点击:

how to delete all files in a folder using default java package

java

提问by Prasath Bala

Am trying to delete all files in a folder and its content. Am using the below code

我正在尝试删除文件夹中的所有文件及其内容。我正在使用下面的代码

 File deltmpfile = new File(destinationpt);
 deltmpfile.delete();

please answer

请回答

回答by Rahul Tripathi

You may try to do something like this:

你可以尝试做这样的事情:

for(File f: directory.listFiles()) 
  f.delete(); 

or

或者

FileUtils.deleteDirectory(new File("directory"));

or

或者

FileUtils.cleanDirectory(directory); 

回答by Incognito

I got this here from SO, I'm sorry I forgot the author (credits to him) but if you want to make/customize your own function, do this.

我是从 SO 那里得到的,很抱歉我忘记了作者(归功于他)但是如果您想制作/自定义您自己的功能,请执行此操作。

    private boolean delete(File pFile) {
        boolean bResult = false;

        if(pFile.exists()) {
            if(pFile.isDirectory()) {
                if(pFile.list().length == 0) {
                    pFile.delete();
                } else {
                    String[] strFiles = pFile.list();

                    for(String strFilename: strFiles) {
                        File fileToDelete = new File(pFile, strFilename);

                        delete(fileToDelete);
                    }
                }
            } else {
                pFile.delete();
            }
        }

        return bResult;
    }