【Hadoop】HDFS编程

1、初始化配置信息:

@Test
    public void init() throws IOException, URISyntaxException, InterruptedException {
        Configuration configuration =new Configuration();
        configuration.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        configuration.set("fs.defaultFS","uri");
        fileSystem=FileSystem.get(new URI("uri"),configuration,"hadoop");//以Hadoop身份
    }

2、创建目录上传下载文件及删除文件:

HDFS读数据

与namenode通信查找元数据,文件的数据块在哪台datanode上

选取最近一台datanode服务器建立socket流

Datanode发送数据(从磁盘读取数据流放入数据包发送出去)

客户端接收数据包 先缓存在磁盘 然后写入文件

 

Hdfa写数据

客户端向namenode发送请求 检查目标文件是否存在,检查目标父目录是否存在。

那么返回是否可以上传数据

客户端对文件进行分块,请求namenode该向那台datanode上传数据

Namenode返回哪台datanode

客户端向datanode请求发送数据,几台datanode建立pipeline

客户端读数据以packet为单位发送数据到第一台datanode,第一台收到packet后向第二台发送,第二台向第三台传,第一台每传入一个packet会放入一个应答队列。

第一个块传完后,重复步骤传第二个块。

@Test
    public void upload() throws IOException, URISyntaxException, InterruptedException {
        init();
        fileSystem.delete(new Path("/input/a.txt"),true);//全部删除目录下文件
        fileSystem.mkdirs(new Path("/input/a.txt"));//创建目录
        fileSystem.copyFromLocalFile(new Path("files/a.txt"),new Path("hdfs://39.105.116.243:9000/input/"));//上传文件

        Path path=new Path("hdfs://39.105.116.243:9000/input/x");//下载文件
        FSDataInputStream dis=fileSystem.open(path);//下载文件
        FileOutputStream fileOutputStream=new FileOutputStream("files/a.txt");
        IOUtils.copy(dis,fileOutputStream);
        fileSystem.copyToLocalFile(path,new Path("files/b.txt"));
    }

3、查看文件目录:

 /*
    * 显示文件*/
    @Test
    public void show() throws InterruptedException, IOException, URISyntaxException {
        init();
        RemoteIterator<LocatedFileStatus> iterator= fileSystem.listFiles(new Path("/"),true);//递归显示文件
        while (iterator.hasNext()){
            LocatedFileStatus fileStatus=iterator.next();
            String string=fileStatus.getPath().getName();
            System.out.println(string);
        }
    }

    /*
    * 显示文件及文件夹*/
    @Test
    public void show1() throws InterruptedException, IOException, URISyntaxException {
        init();
        FileStatus[] fileStatuses=fileSystem.listStatus(new Path("/"));//显示文件夹
        for (FileStatus status:fileStatuses){
            String string=status.getPath().getName();
            System.out.println(string);
        }
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值