Java - 如何删除文件夹

  Java删除文件很简单,只需要File.delete()即可,但是如果要删除文件夹,Java要求这个文件夹必须为空。。所以如果要删除一个有文件的文件夹,必须得自己写个函数递归处理,参考:


下面文章转载自 http://www.mkyong.com/java/how-to-delete-directory-in-java/



To delete a directory, you can simply use the File.delete(), but the directory must be empty in order to delete it.

Often times, you may require to perform recursive delete in a directory, which means all it’s sub-directories and files should be delete as well, see below example :

Directory recursive delete example

Delete the directory named “C:\\mkyong-new“, and all it’s sub-directories and files as well. The code is self-explanatory and well documented, it should be easy to understand.

package com.mkyong.file;
 
import java.io.File;
import java.io.IOException;
 
public class DeleteDirectoryExample
{
    private static final String SRC_FOLDER = "C:\\mkyong-new";
 
    public static void main(String[] args)
    {	
 
    	File directory = new File(SRC_FOLDER);
 
    	//make sure directory exists
    	if(!directory.exists()){
 
           System.out.println("Directory does not exist.");
           System.exit(0);
 
        }else{
 
           try{
 
               delete(directory);
 
           }catch(IOException e){
               e.printStackTrace();
               System.exit(0);
           }
        }
 
    	System.out.println("Done");
    }
 
    public static void delete(File file)
    	throws IOException{
 
    	if(file.isDirectory()){
 
    		//directory is empty, then delete it
    		if(file.list().length==0){
 
    		   file.delete();
    		   System.out.println("Directory is deleted : " 
                                                 + file.getAbsolutePath());
 
    		}else{
 
    		   //list all the directory contents
        	   String files[] = file.list();
 
        	   for (String temp : files) {
        	      //construct the file structure
        	      File fileDelete = new File(file, temp);
 
        	      //recursive delete
        	     delete(fileDelete);
        	   }
 
        	   //check the directory again, if empty then delete it
        	   if(file.list().length==0){
           	     file.delete();
        	     System.out.println("Directory is deleted : " 
                                                  + file.getAbsolutePath());
        	   }
    		}
 
    	}else{
    		//if file, then delete it
    		file.delete();
    		System.out.println("File is deleted : " + file.getAbsolutePath());
    	}
    }
}


 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值