【Hadoop—06】Java操作HDFS的API

导读:本篇文章讲解 【Hadoop—06】Java操作HDFS的API,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

1. 编写Demo

  1. 客户端安装hadoop:虽然我们编写 java 代码的电脑是作为客户端去连接 hdfs 服务器,但是 hdfs 要求如果要读写hdfs就需要在客户端也安装 hadoop。但是hdfs官方又没有Windows版的安装包,所以需要在windows系统中安装与hadoop服务器对应版本的 winutils.exehdfs.dll

    链接:https://pan.baidu.com/s/1xE-RmvqQfQcAIXeK5wsytg 提取码:finv

    下载上面的压缩包并在解压在非中文路径下,然后配置环境变量。
    在这里插入图片描述

  2. 打开IDEA,创建mave。
    在这里插入图片描述
    在这里插入图片描述

    -Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true
    

    在这里插入图片描述

  3. pom.xml中添加依赖:

    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <!-- 注意版本和Hadoop服务器版本一致,否则可能会不兼容 -->
        <version>3.1.3</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.30</version>
    </dependency>
    
  4. 在项目的src/main/resource目录下创建文件log4j.properties,并在文件中写入:

    log4j.rootLogger=INFO, stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
    log4j.appender.logfile=org.apache.log4j.FileAppender
    log4j.appender.logfile.File=target/hadoop-client.log
    log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
    log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
    
  5. 在项目的src/main/java目录下创建文件HDFSClient.java,并在文件中写入:

    package com.hao;
    
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.FileSystem;
    import org.apache.hadoop.fs.Path;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.net.URI;
    import java.net.URISyntaxException;
    
    public class HDFSClient {
    
        private FileSystem fs;
    
        @Before
        /**
         * 获取客户端对象
         */
        public void init() throws URISyntaxException, IOException, InterruptedException {
            Configuration configuration = new Configuration();
            String uri = "hdfs://hadoop102:8020";  // 连接的集群NN地址
            String user = "tengyer";  // 用户
    
            fs = FileSystem.get(new URI(uri), configuration, user);
        }
    
        @After
        /**
         * 关闭资源
         */
        public void close() throws IOException {
            fs.close();
        }
    
        @Test
        public void testMkdirs() throws IOException, URISyntaxException, InterruptedException {
            // 在HDFS上创建一个文件夹
            fs.mkdirs(new Path("/java"));
        }
    }
    
  6. 登入hdfs的web页面查看:http://192.168.10.102:9870,能够看到在根目录下创建了java文件夹。

2. 常用 Java API

(1) 创建文件夹

@Test
public void testMkdirs() throws IOException, URISyntaxException, InterruptedException {
    // 在HDFS上创建一个文件夹
    fs.mkdirs(new Path("/xiyouji/huaguoshan"));
}

(2)上传文件

@Test
/**
 * 测试上传
 */
public void testPut() throws IOException {
    boolean delSrc = false;  // 上传完毕是否删除原数据
    boolean overwrite = false; // 如果hdfs上已有该文件,是否允许覆盖,(不允许覆盖时,如果目的地已经存在该文件,则抛出异常)
    Path src = new Path("/app/testData/sunwukong.txt"); // 源数据路径
    Path dst = new Path("/xiyouji/huaguoshan/"); // 目的地路径,可以加上协议写成完整路径 hdfs://hadoop102:8020/xiyouji/huaguoshan/,也可以不加
    fs.copyFromLocalFile(delSrc, overwrite, src, dst);
}

(3)下载文件

@Test
/**
 * 测试从hdfs下载
 */
public void testGet() throws IOException {
    boolean delSrc = false; // 下载完毕后,是否删除hdfs上的源文件
    Path src = new Path("/xiyouji/huaguoshan/sunwukong.txt");  // hdfs源数据路径(文件或文件夹),也可以加上hdfs://hadoop102/写成完整路径
    // 目的地路径是一个文件夹,程序会将hdfs中的文件下载到该文件夹。如果配置的有CRC校验,则文件还会同时生成一个crc校验文件
    Path dst = new Path("/app/testData/"); // 目的文件夹路径
    boolean useRawLocalFileSystem = true;  // 是否使用本地校验?false则会使用hdfs的CRC文件校验。true则使用本地校验,即不校验
    fs.copyToLocalFile(delSrc, src, dst, useRawLocalFileSystem);
}

(4)删除hdfs的文件

@Test
/**
 * 测试删除hdfs文件
 */
public void testRM() throws IOException {
    Path path = new Path("/xiyouji/huaguoshan/sunwukong.txt");  // 要删除的路径(文件或文件夹)
    boolean recursive = false;  // 是否递归删除,删除非空文件夹时需要递归删除文件夹下的内容,类似 rm 的 -r 参数。删除文件或空文件夹时可以不递归
    fs.delete(path, recursive);
}

(5)文件移动和重命名

@Test
/**
 * 测试移动和重命名hdfs文件
 */
public void testMV() throws IOException {
    //        Path src = new Path("/xiyouji/huaguoshan/sunwukong.txt");
    //        Path dst = new Path("/xiyouji/huaguoshan/meihouwang.txt");
    //        fs.rename(src, dst);  // 重命名

    // 文件移动位置并重命名
    fs.rename(new Path("/xiyouji/huaguoshan/meihouwang.txt"), new Path("/xiyouji/sunxingzhe.txt"));
}

(6)类似ls命令获取目录信息

@Test
@Test
/**
 * 列举文件夹下文件详情, ls 命令
 */
public void testLS() throws IOException {
    Path path = new Path("/xiyouji");
    boolean recursive = false; // 是否递归
    // 类似ls命令,返回值是一个迭代器
    RemoteIterator<LocatedFileStatus> listFilesIterator = fs.listFiles(path, recursive);
    while(listFilesIterator.hasNext()) {
        LocatedFileStatus fileStatus = listFilesIterator.next();  // 获取到文件属性
        Path filePath = fileStatus.getPath();
        FsPermission permission = fileStatus.getPermission(); // 获取权限信息
        String owner = fileStatus.getOwner(); // 拥有者
        String group = fileStatus.getGroup(); // 组用户
     	long len = fileStatus.getLen(); // 文件大小,单位为B
     	long time = fileStatus.getModificationTime(); // 上次修改时间:返回的是时间戳
        long blockSize = fileStatus.getBlockSize(); // 块大小
        short replication = fileStatus.getReplication(); // 副本数
        String name = fileStatus.getPath().getName(); // 文件名

		BlockLocation[] blockLocations = fileStatus.getBlockLocations();
        System.out.println(Arrays.toString(blockLocations)); // 输出数据存在哪些块中
    }
}

(7)只获取目录中的文件

@Test
/**
 * 通过listStatus获取指定路径下的所有文件属性
 */
public void testFileStatus() throws IOException {
    Path path = new Path("/jinguo");
    FileStatus[] fileStatuses = fs.listStatus(path);
    for (FileStatus fileStatus : fileStatuses) {
        System.out.println("------------------------");
        System.out.println(fileStatus.getPath().getName());  // 获取文件名称
        if (fileStatus.isFile()) {  // 判断是文件还是文件夹
            System.out.println("是一个文件");
        }
    }
}

3. 修改配置项

3.1 方式一:使用配置文件配置

在resources下创建hdfs-site.xml

<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <!-- 配置副本数量,程序中的hdfs-site.xml会覆盖hadoop软件中的该项值 -->
    <property>
        <name>dfs.replication</name>
        <value>4</value>
    </property>
</configuration>

3.2 方式二:使用java代码配置

对Configuration类的实例化对象设置键值对即可:

Configuration configuration = new Configuration();
// 将文件副本数量配置为5
configuration.set("dfs.replication", "5");

String uri = "hdfs://hadoop102:8020";  // 连接的集群NN地址
String user = "tengyer";  // 用户
fs = FileSystem.get(new URI(uri), configuration, user);

3.3 关于配置的优先级说明

从上往下,优先级依次变高,后面的会覆盖前面的。

● hadoop软件中的hdfs-default.xml
● hadoop软件中的hdfs-site.xml
● 在项目的resources下的hdfs-site.xml配置文件
● 程序中的Configuration对象中配置的值

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/84551.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!