当前位置: 移动技术网 > IT编程>开发语言>Java > JAVA实现将磁盘中所有空文件夹进行删除的代码

JAVA实现将磁盘中所有空文件夹进行删除的代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

实现代码一、

import java.io.file;
import java.io.*;
public class delnulldir {
	public void showdir(file f){
		for (file f1:f.listfiles()){
			if(f1.isdirectory()){
				showdir(f1);
				//一直递归到最后的目录
				if(f1.listfiles().length==0){
					//如果是文件夹里面没有文件证明是空文件,进行删除
					f1.delete();
				}
			}
		}
	}
	/**
 * 
 * 把磁盘中所有空的文件夹进行删除
 */
	public static void main(string[] args) {
		file f = new file("f:\\360cloudui\\");
		new delnulldir().showdir(f);
	}
}

实现代码二、

import java.io.bufferedoutputstream;
import java.io.file;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.unsupportedencodingexception;
import java.util.date;
/**
 * description:递归方式,扫描并删除磁盘中的空文件夹
 *(c盘中的一些空文件夹是系统文件夹,删除多次后空文件夹数量不变,则停止此程序)
 * */
public class delemptyfolders {
  //空文件夹的绝对路径
  private static stringbuffer paths;
  //本次扫描的空文件夹的数量
  private static int cnt;
  public static void main(string[] args) {
    boolean flag = true;
    do{
      cnt = 0;
      paths = new stringbuffer();
      long start = new date().gettime();
      system.out.println("正在扫描......");
      //要扫描的磁盘
      file disk = new file("c:/");
      //日志文件的位置
      file log = new file("d:/scanlog_c.txt");
      try {
        //扫描磁盘
        scanemptyfolders(disk);
        //空文件夹数大于0时,将文件夹的绝对路径记录到日志中并再扫描一次;否则停止扫描
        if(cnt > 0){
          filewrite(paths.tostring(), log);
        }else{
          flag = false;
        }
      } catch (filenotfoundexception e1) {
        e1.printstacktrace();
      } catch (ioexception e2) {
        e2.printstacktrace();
      }
      long end = new date().gettime();
      system.out.println("本次扫描完毕,耗时:"+(end-start)/1000+" 秒,共删除:"+cnt+" 个空文件夹!\n");
    }while(flag);
  }
  /**
   * todo:递归扫描空文件夹
   * @throws unsupportedencodingexception
   * */
  private static void scanemptyfolders(file file) throws unsupportedencodingexception{
    if(file != null && file.isdirectory()){
      file[] files = file.listfiles();
      //非空文件夹
      if(files != null){
        if(files.length > 0){
          for (file temp : files) {
            scanemptyfolders(temp);
          }
        }else{
          system.out.println(file.getabsolutepath());
          //记录日志
          paths.append(new string((file.getabsolutepath()+"\r\n").getbytes(),"utf-8"));
          cnt++;
          //删除空文件夹
          file.delete();
        }
      }
    }
  }
  /**
   * todo:将字符串写入文本文件
   * @throws ioexception
   * */
  private static void filewrite(string info,file file) throws ioexception{
    fileoutputstream fos = new fileoutputstream(file);
    bufferedoutputstream bos = new bufferedoutputstream(fos);
    bos.write(info.getbytes());
    bos.flush();
    bos.close();
    fos.close();
  }
}

以上就是java删除空文件夹的实现代码,需要的朋友可以参考一下。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网