如何删除空文件夹Java_JAVA实现将磁盘中所有空文件夹进行删除的代码
實現代碼一、
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刪除空文件夾的實現代碼,需要的朋友可以參考一下。
希望與廣大網友互動??
點此進行留言吧!
總結
以上是生活随笔為你收集整理的如何删除空文件夹Java_JAVA实现将磁盘中所有空文件夹进行删除的代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如约而至 Nexus 6 的 Andro
- 下一篇: java没有对象可以调用方法吗_在没有括