5 HDFS--JavaAPI

hdfs在生产应用中主要是客户端的开发,其核心步骤是从hdfs提供的api中构造一个HDFS的访问客户端对象,然后通过该客户端对象操作(增删改查)HDFS上的文件

1 搭建maven开发环境

pom.xml参考

    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-client</artifactId>
      <version>2.6.5</version>
    </dependency>

2 windows测试搭建

下载winutils地址https://github.com/amihalik/hadoop-common-2.6.0-bin
配置环境变量
增加用户变量HADOOP_HOME,值是下载的zip包解压的目录,
然后在系统变量path里增加%HADOOP_HOME%\bin 即可。
注意重启电脑才能生效

3 CRUD

HdfsClient.java

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.junit.Before;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;

public class HdfsClient {

    FileSystem fs = null;

    @Before
    public void init() throws Exception {

        // 构造一个配置参数对象,设置一个参数:我们要访问的hdfs的URI
        // 从而FileSystem.get()方法就知道应该是去构造一个访问hdfs文件系统的客户端,以及hdfs的访问地址
        Configuration conf = new Configuration();

        // 如果这样去获取,那conf里面就可以不要配"fs.defaultFS"参数,而且,这个客户端的身份标识已经是root用户
        fs = FileSystem.get(new URI("hdfs://192.168.147.10:9000"), conf, "root");
    }

    /**
     * 往hdfs上传文件
     *
     * @throws Exception
     */
    @Test
    public void testAddFileToHdfs() throws Exception {

        // 要上传的文件所在的本地路径
        Path src = new Path("C:\\Users\\User\\Desktop\\aa.txt");
        // 要上传到hdfs的目标路径
        Path dst = new Path("/aaa/aa.txt");
        fs.copyFromLocalFile(src, dst);
        fs.close();
    }

    /**
     * 从hdfs中复制文件到本地文件系统
     *
     * @throws IOException
     * @throws IllegalArgumentException
     */
    @Test
    public void testDownloadFileToLocal() throws IllegalArgumentException, IOException {
        fs.copyToLocalFile(new Path("/aaa"), new Path("C:\\Users\\User\\Desktop\\bb"));
        fs.close();
    }

    @Test
    public void testMkdirAndDeleteAndRename() throws IllegalArgumentException, IOException {

        // 创建目录
        fs.mkdirs(new Path("/a1/b1/c1"));

        // 删除文件夹 ,如果是非空文件夹,参数2必须给值true
        fs.delete(new Path("/aaa"), true);

        // 重命名文件或文件夹
        fs.rename(new Path("/a1"), new Path("/a2"));
    }

    /**
     * 查看目录信息,只显示文件
     *
     * @throws IOException
     * @throws IllegalArgumentException
     * @throws FileNotFoundException
     */
    @Test
    public void testListFiles() throws FileNotFoundException, IllegalArgumentException, IOException {

        // 返回为迭代器,而不是List之类的容器
        RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);
        while (listFiles.hasNext()) {
            LocatedFileStatus fileStatus = listFiles.next();
            System.out.println(fileStatus.getPath().getName());
            System.out.println(fileStatus.getBlockSize());
            System.out.println(fileStatus.getPermission());
            System.out.println(fileStatus.getLen());
            BlockLocation[] blockLocations = fileStatus.getBlockLocations();
            for (BlockLocation bl : blockLocations) {
                System.out.println("block-length:" + bl.getLength() + "--" + "block-offset:" + bl.getOffset());
                String[] hosts = bl.getHosts();
                for (String host : hosts) {
                    System.out.println(host);
                }
            }
            System.out.println("--------------打印的分割线--------------");
        }
    }

    /**
     * 查看文件及文件夹信息
     *
     * @throws IOException
     * @throws IllegalArgumentException
     * @throws FileNotFoundException
     */
    @Test
    public void testListAll() throws FileNotFoundException, IllegalArgumentException, IOException {

        FileStatus[] listStatus = fs.listStatus(new Path("/"));

        String flag = "d--             ";
        for (FileStatus fstatus : listStatus) {
            if (fstatus.isFile()) flag = "f--         ";
            System.out.println(flag + fstatus.getPath().getName());
        }
    }

}

4 流操作

StreamAccess .java

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;

public class StreamAccess {
    FileSystem fs = null;

    @Before
    public void init() throws Exception {
        Configuration conf = new Configuration();
        fs = FileSystem.get(new URI("hdfs://192.168.147.10:9000"), conf, "root");
    }

    @Test
    public void testDownLoadFileToLocal() throws IllegalArgumentException, IOException {
        //先获取一个文件的输入流----针对hdfs上的
        FSDataInputStream in = fs.open(new Path("/aa.txt"));

        //再构造一个文件的输出流----针对本地的
        FileOutputStream out = new FileOutputStream(new File("C:\\Users\\User\\Desktop\\cc.txt"));

        //再将输入流中数据传输到输出流
        IOUtils.copyBytes(in, out, 4096);
    }

    /**
     * hdfs支持随机定位进行文件读取,而且可以方便地读取指定长度
     * 用于上层分布式运算框架并发处理数据
     *
     * @throws IllegalArgumentException
     * @throws IOException              }
     */
    @Test
    public void testRandomAccess() throws IllegalArgumentException, IOException {
        //先获取一个文件的输入流----针对hdfs上的
        FSDataInputStream in = fs.open(new Path("/aa.txt"));

        //可以将流的起始偏移量进行自定义,相当于从文件哪里开始读
        in.seek(10);

        //再构造一个文件的输出流----针对本地的
        FileOutputStream out = new FileOutputStream(new File("C:\\Users\\User\\Desktop\\cc1.txt"));

        IOUtils.copyBytes(in, out, 19L, true);
    }

    /**
     * 显示hdfs上文件的内容
     *
     * @throws IOException
     * @throws IllegalArgumentException
     */
    @Test
    public void testCat() throws IllegalArgumentException, IOException {

        FSDataInputStream in = fs.open(new Path("/aa.txt"));

        IOUtils.copyBytes(in, System.out, 1024);
    }

}

posted on 2019-07-19 15:55  农夫三拳有點疼  阅读(15)  评论(0编辑  收藏  举报

导航