idea上HDFS API练习之列出指定目录下的文件以及块的信息

代码:

package com.dtinone.hadooptest1.hsfsapi;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;

public class CatFileAndBlockMessage {

    public static void main(String[] args) throws Exception {

        Configuration conf = new Configuration();
        System.setProperty("HADOOP_USER_NAME", "hadoop");
        conf.set("fs.defaultFS", "hdfs://master:9000");
        FileSystem fs = FileSystem.get(conf);

        /**
         * 列出指定的目录下的所有文件
         */
        RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);
        while (listFiles.hasNext()) {
            LocatedFileStatus file = listFiles.next();


            System.out.println(file.getPath() + "\t");
            System.out.println(file.getPath().getName() + "\t");
            System.out.println(file.getLen() + "\t");
            System.out.println(file.getReplication() + "\t");

            /**
             * blockLocations的长度是几?  是什么意义?
             *
             * 块的数量
             */
            BlockLocation[] blockLocations = file.getBlockLocations();
            System.out.println(blockLocations.length + "\t");

            for (BlockLocation bl : blockLocations) {
                String[] hosts = bl.getHosts();

                System.out.print(hosts[0] + "-" + hosts[1] + "\t");
            }
            System.out.println();

        }
    }
}

执行结果:

hdfs://master:9000/home/a.txt	
a.txt	
73	
3	
1	
localhost-slave2	
hdfs://master:9000/home/get.txt	
get.txt	
21	
3	
1	
slave2-slave1	
hdfs://master:9000/input/wordCount/word.txt	
word.txt	
840	
3	
1	
slave3-slave2	
hdfs://master:9000/opt/data/c.txt	
c.txt	
81	
4	
1	
localhost-slave1	
hdfs://master:9000/opt/data/plus.txt	
plus.txt	
146	
3	
1	
localhost-slave1	
hdfs://master:9000/output/wordCount/1/_SUCCESS	
_SUCCESS	
0	
3	
0	

hdfs://master:9000/output/wordCount/1/part-r-00000	
part-r-00000	
776	
3	
1	
localhost-slave3	

结果解释:
文件路径:hdfs://master:9000/home/a.txt
文件名: a.txt
文件长度: 73
副本个数: 3
块数量: 1
块所在节点: localhost-slave2

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值