hdfs客户端Api上传下载查看文件信息

上传文件--copyfromLocalFile

 @Test
    public  void hdfscopyfromlocal() throws IOException {
        //上传文件
        //src源文件即本地文件
        //dit为目标文件
        fs.copyFromLocalFile(new Path("E:/test.txt"),new Path("/"));
    }

下载文件---copytoLocalFile

@Test
    public void hdfscopytolocal() throws IOException {
        //下载文件
        fs.copyToLocalFile(new Path("/input"),new Path("E:/"));
    }

其中我们可以通过代码修改副本参数

public void init() throws URISyntaxException, IOException, InterruptedException {
        Configuration conf = new Configuration();
        //代码设置副本参数
//        conf.set("dfs.replication","2");
        fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), conf, "root");
    }


注意要点参数优先级 排序:

代码设置的值>用户自定义配置文件>服务器默认配置

删除文件或文件夹----delete

@Test
    public void remove() throws IOException {
        //删除文件 recursive:bool判断是否递归删除
        fs.delete(new Path("/api_test"),true);
    }

 查看文件信息--listfiles

@Test
    public void check(){
        RemoteIterator<LocatedFileStatus> ite = null;
        try {
            ite = fs.listFiles(new Path("/"), true);
            while (ite.hasNext()){
                LocatedFileStatus status = ite.next();
                //获取名字
                String name = status.getPath().getName();
                //获取文件长度
                long len = status.getLen();
                //获取权限名称
                FsPermission permission = status.getPermission();
                //获取分组
                String group = status.getGroup();
                //获取块信息
                BlockLocation[] blockLocations = status.getBlockLocations();
                System.out.println(name);
                System.out.println(len);
                System.out.println(permission);
                System.out.println(group);
                for (BlockLocation blockLocation : blockLocations) {
                    String[] hosts = blockLocation.getHosts();
                    for (String host : hosts) {
                        System.out.println(host);
                    }
                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

判断是否是文件--filestatues,isfile

@Test
    public void check_isfile() throws IOException {
        FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
        for (FileStatus fileStatus : fileStatuses) {
            if (fileStatus.isFile()){
                System.out.println("f:"+fileStatus.getPath().getName());
            }
            else{
                System.out.println("d:"+fileStatus.getPath().getName());
            }
        }

    }

总结:

通过对代码的运行进行验证是否是正确的 

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值