hadoop3.x HDFS java遍历文件详细信息(FileSystem.listFiles)

介绍

语法:

RemoteIterator<LocatedFileStatus> FileSystem.listFiles(Path f, boolean recursive)

形参:

  • Path f:目录
  • recursive:是否递归

返回值: RemoteIterator<LocatedFileStatus> 迭代器

LocatedFileStatus 是 FileStatus 的子类,可获取权限、所属用户、所属用户组、文件大小、创建时间、上次修改时间、副本数量、block大小、文件全路径名等

还有 BlockLocation[] 属性,用于记录 Block 的网络位置,包括块副本所在的主机,与块关联的文件偏移量,长度,是否已损坏等。

当 recursive 为 true,递归 列出目录(及子目录)下 所有文件;为 false,只列出该目录下 所有文件

注意:不会列出目录

java 代码

@Test
public void listFiles() throws Exception{

    //获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hadoop1:8020"), configuration, "root");

    /*
    获取文件详情
    第二个参数:true递归显示
     */
    RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);

    while(listFiles.hasNext()){
        LocatedFileStatus status = listFiles.next();

        // 权限
        System.out.print(status.getPermission()+"\t");
        // 所属用户
        System.out.print(status.getOwner()+"\t");
        // 所属用户组
        System.out.print(status.getGroup()+"\t");
        // 大小
        long len=status.getLen();
        String unit="B";
        if(len> 1024*1024){
            len=len/1024/1024;
            unit="MB";
        }else if(len> 1024){
            len=len/1024;
            unit="KB";
        }
        System.out.print(len+unit+"\t");
        // 上次修改时间
        Date date=new Date(status.getModificationTime());
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String time=sdf.format(date);
        System.out.print(time+"\t");
        // 副本数量
        System.out.print(status.getReplication()+"\t");
        // block大小
        long size=status.getBlockSize()/1024/1024;
        System.out.print(size+"MB\t");
        // 文件名称
        System.out.print(status.getPath()+"\t");

        // 获取块信息。BlockLocation记录块的网络位置,包括块副本所在的主机,与块关联的文件偏移量,长度,是否已损坏
        BlockLocation[] blockLocations = status.getBlockLocations();

        for (BlockLocation blockLocation : blockLocations) {

            // 获取块存储的主机节点
            String[] hosts = blockLocation.getHosts();

            for (String host : hosts) {
                System.out.print(host+"\t");
            }
        }

        System.out.println();
    }

    //关闭
    fs.close();
}

原文出处:/show_1IXacU6vlli.html