递归删除空文件、空目录

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);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/YZY_001/article/details/82078135
今日推荐