JAVA删除HDFS目录(回收站)

背景

  • 在项目中用到了Hdfs Java Api来删除目录,使用的是fs.delete(new Path(targetLocation), true),而delete方法默认的不进回收站的,相当于hdfs命令: hdfs dfs -rm -r -skipTrash。
  • 在验证程序功能初期时,此举很危险还是进行回收站稳妥点。

代码

  • 项目中获取hdfs client即FileSystem对象没有采用source hadoop xml的方式,而是通过手动命令行的设置,这样的好处是不用维护多个集群的hadoop配置文件。
  • 代码中访问hdfs采用的是ha域名,因此需要设置的参数比较多。
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.Trash;
import org.apache.hadoop.security.UserGroupInformation;
import java.io.IOException;


public class Test {
    public static final String USER_KEY = "<你的kerberos principal>";
    public static final String KEY_TAB_PATH = "<你的kerberos keytab具体目录路径>";
    static Configuration conf = new Configuration();
    static {
        //在window下运行一般需要设置
        System.setProperty("java.security.krb5.conf", "<你的krb5.conf具体目录路径>");
        conf.set("dfs.namenode.kerberos.principal", "<你的kerberos principal>");
        conf.set("dfs.namenode.kerberos.principal.pattern", "*");
        conf.set("hadoop.security.authentication", "kerberos");
        //这里需要显式设定,否则删除失败(isEnable=false)
        conf.set("fs.trash.interval","1");
        conf.set("fs.defaultFS", "hdfs://<你的Hdfs ha名>");
        conf.set("dfs.client.failover.proxy.provider.<你的Hdfs ha名>","org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
        conf.set("dfs.ha.namenodes.<你的Hdfs ha名>","<你的Hdfs namenodes列表>");
        conf.set("dfs.namenode.rpc-address.<你的Hdfs ha名>.<你的Hdfs namenodes列表[0]>","<你的Hdfs namenodes hostname列表[0]>:8020");
        conf.set("dfs.namenode.rpc-address.<你的Hdfs ha名>.<你的Hdfs namenodes列表[1]>","<你的Hdfs namenodes hostname列表[1]>:8020");
        conf.set("dfs.nameservices","<你的Hdfs ha名>");

        try {
            UserGroupInformation.setConfiguration(conf);
            UserGroupInformation.loginUserFromKeytab(USER_KEY, KEY_TAB_PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        FileSystem fs = FileSystem.get(conf);
        //待删除的目录
        String targetLocation = "/tmp/hive";
        Trash trash = new Trash(fs,fs.getConf());
        //如何移除到回收站成功则返回true,反正返回false
        boolean deleteHdfsPath= trash.moveToTrash(new Path(targetLocation));
        
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。