遞迴刪除空檔案、空目錄
阿新 • • 發佈:2018-12-24
package com.ghgj.cn.zy;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop .fs.Path;
public class deleteEmpty {
// 遞迴刪除空檔案空目錄
public static void main(String[] args) throws IOException, InterruptedException, URISyntaxException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop01:9000"), conf, "hadoop");
delEmpty(fs, new Path("/tt" ));
}
static void delEmpty(FileSystem fs, Path path) throws FileNotFoundException, IOException{
FileStatus[] listStatus = fs.listStatus(path);
if(listStatus.length==0){
fs.delete(path, false);
}else{
for(FileStatus fss:listStatus){
Path p = fss.getPath ();
if(fss.isFile()){
if(fss.getLen()==0){
fs.delete(p, false);
}
}else{
delEmpty(fs, p);
}
}
//再次判讀最外層是否為空目錄
FileStatus [] list =fs.listStatus(path);
System.out.println(list.length);
if(list.length==0){
fs.delete(path, false);
}
// fs.delete(path, false);
}
}
}