• HDFS Java API


    1.简介

    想要使用 HDFS API,需要导入依赖 `hadoop-client`。如果是 CDH 版本的 Hadoop,还需要额外指明其仓库地址:

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0</modelVersion>
    6. <groupId>com.shangjack</groupId>
    7. <artifactId>hdfs-java-api</artifactId>
    8. <version>1.0</version>
    9. <properties>
    10. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    11. <hadoop.version>3.3.2</hadoop.version>
    12. </properties>
    13. <!---配置CDH仓库地址-->
    14. <repositories>
    15. <repository>
    16. <id>cloudera</id>
    17. <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
    18. </repository>
    19. </repositories>
    20. <dependencies>
    21. <!--Hadoop-client-->
    22. <dependency>
    23. <groupId>org.apache.hadoop</groupId>
    24. <artifactId>hadoop-client</artifactId>
    25. <version>${hadoop.version}</version>
    26. </dependency>
    27. <dependency>
    28. <groupId>junit</groupId>
    29. <artifactId>junit</artifactId>
    30. <version>4.12</version>
    31. <scope>test</scope>
    32. </dependency>
    33. </dependencies>
    34. </project>

    2.API的使用

    2.1 FileSystem

    FileSystem 是所有 HDFS 操作的主入口。由于之后的每个单元测试都需要用到它,这里使用 `@Before` 注解进行标注。

    1. private static final String HDFS_PATH = "hdfs://master:8020";
    2. private static final String HDFS_USER = "root";
    3. private static FileSystem fileSystem;
    4. @Before
    5. public void prepare() {
    6. try {
    7. Configuration configuration = new Configuration();
    8. // 这里我启动的是单节点的 Hadoop,所以副本系数设置为 1,默认值为 3
    9. configuration.set("dfs.replication", "1");
    10. fileSystem = FileSystem.get(new URI(HDFS_PATH), configuration, HDFS_USER);
    11. } catch (IOException e) {
    12. e.printStackTrace();
    13. } catch (InterruptedException e) {
    14. e.printStackTrace();
    15. } catch (URISyntaxException e) {
    16. e.printStackTrace();
    17. }
    18. }
    19. @After
    20. public void destroy() {
    21. fileSystem = null;
    22. }

    2.2 创建目录

    支持递归创建目录:

    1. @Test
    2. public void mkDir() throws Exception {
    3. fileSystem.mkdirs(new Path("/hdfs-api/test0/"));
    4. }

    2.3 创建指定权限的目录

    `FsPermission(FsAction u, FsAction g, FsAction o)` 的三个参数分别对应:创建者权限,同组其他用户权限,其他用户权限,权限值定义在 `FsAction` 枚举类中。

    1. @Test
    2. public void mkDirWithPermission() throws Exception {
    3. fileSystem.mkdirs(new Path("/hdfs-api/test1/"),
    4. new FsPermission(FsAction.READ_WRITE, FsAction.READ, FsAction.READ));
    5. }

    2.4 创建文件,并写入内容

    1. @Test
    2. public void create() throws Exception {
    3. // 如果文件存在,默认会覆盖, 可以通过第二个参数进行控制。第三个参数可以控制使用缓冲区的大小
    4. FSDataOutputStream out = fileSystem.create(new Path("/hdfs-api/test/a.txt"),
    5. true, 4096);
    6. out.write("hello hadoop!".getBytes());
    7. out.write("hello spark!".getBytes());
    8. out.write("hello flink!".getBytes());
    9. // 强制将缓冲区中内容刷出
    10. out.flush();
    11. out.close();
    12. }

    2.5 判断文件是否存在

    1. @Test
    2. public void exist() throws Exception {
    3. boolean exists = fileSystem.exists(new Path("/hdfs-api/test/a.txt"));
    4. System.out.println(exists);
    5. }

    2.6 查看文件内容

    查看小文本文件的内容,直接转换成字符串后输出:

    1. @Test
    2. public void readToString() throws Exception {
    3. FSDataInputStream inputStream = fileSystem.open(new Path("/hdfs-api/test/a.txt"));
    4. String context = inputStreamToString(inputStream, "utf-8");
    5. System.out.println(context);
    6. }

    `inputStreamToString` 是一个自定义方法,代码如下:

    1. /**
    2. * 把输入流转换为指定编码的字符
    3. *
    4. * @param inputStream 输入流
    5. * @param encode      指定编码类型
    6. */
    7. private static String inputStreamToString(InputStream inputStream, String encode) {
    8. try {
    9. if (encode == null || ("".equals(encode))) {
    10. encode = "utf-8";
    11. }
    12. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, encode));
    13. StringBuilder builder = new StringBuilder();
    14. String str = "";
    15. while ((str = reader.readLine()) != null) {
    16. builder.append(str).append("\n");
    17. }
    18. return builder.toString();
    19. } catch (IOException e) {
    20. e.printStackTrace();
    21. }
    22. return null;
    23. }

    2.7 文件重命名

    1. @Test
    2. public void rename() throws Exception {
    3. Path oldPath = new Path("/hdfs-api/test/a.txt");
    4. Path newPath = new Path("/hdfs-api/test/b.txt");
    5. boolean result = fileSystem.rename(oldPath, newPath);
    6. System.out.println(result);
    7. }

    2.8 删除目录或文件

    1. public void delete() throws Exception {
    2. /*
    3. *  第二个参数代表是否递归删除
    4. * +  如果 path 是一个目录且递归删除为 true, 则删除该目录及其中所有文件;
    5. * +  如果 path 是一个目录但递归删除为 false,则会则抛出异常。
    6. */
    7. boolean result = fileSystem.delete(new Path("/hdfs-api/test/b.txt"), true);
    8. System.out.println(result);
    9. }

    2.9 上传文件到HDFS

    1. @Test
    2. public void copyFromLocalFile() throws Exception {
    3. // 如果指定的是目录,则会把目录及其中的文件都复制到指定目录下
    4. Path src = new Path("D:\\BigData-Notes\\notes\\installation");
    5. Path dst = new Path("/hdfs-api/test/");
    6. fileSystem.copyFromLocalFile(src, dst);
    7. }

    2.10 上传大文件并显示上传进度

    1. @Test
    2. public void copyFromLocalBigFile() throws Exception {
    3. File file = new File("D:\\kafka.tgz");
    4. final float fileSize = file.length();
    5. InputStream in = new BufferedInputStream(new FileInputStream(file));
    6. FSDataOutputStream out = fileSystem.create(new Path("/hdfs-api/test/kafka5.tgz"),
    7. new Progressable() {
    8. long fileCount = 0;
    9. public void progress() {
    10. fileCount++;
    11. // progress 方法每上传大约 64KB 的数据后就会被调用一次
    12. System.out.println("上传进度:" + (fileCount * 64 * 1024 / fileSize) * 100 + " %");
    13. }
    14. });
    15. IOUtils.copyBytes(in, out, 4096);
    16. }

    2.11 从HDFS上下载文件

    1. @Test
    2. public void copyToLocalFile() throws Exception {
    3. Path src = new Path("/hdfs-api/test/kafka.tgz");
    4. Path dst = new Path("D:\\app\\");
    5. /*
    6. * 第一个参数控制下载完成后是否删除源文件,默认是 true,即删除;
    7. * 最后一个参数表示是否将 RawLocalFileSystem 用作本地文件系统;
    8. * RawLocalFileSystem 默认为 false,通常情况下可以不设置,
    9. * 但如果你在执行时候抛出 NullPointerException 异常,则代表你的文件系统与程序可能存在不兼容的情况 (window 下常见),
    10. * 此时可以将 RawLocalFileSystem 设置为 true
    11. */
    12. fileSystem.copyToLocalFile(false, src, dst, true);
    13. }

    2.12 查看指定目录下所有文件的信息

    1. public void listFiles() throws Exception {
    2. FileStatus[] statuses = fileSystem.listStatus(new Path("/hdfs-api"));
    3. for (FileStatus fileStatus : statuses) {
    4. //fileStatus 的 toString 方法被重写过,直接打印可以看到所有信息
    5. System.out.println(fileStatus.toString());
    6. }
    7. }

    `FileStatus` 中包含了文件的基本信息,比如文件路径,是否是文件夹,修改时间,访问时间,所有者,所属组,文件权限,是否是符号链接等,输出内容示例如下:

    1. FileStatus{
    2. path=hdfs://master:8020/hdfs-api/test;
    3. isDirectory=true;
    4. modification_time=1556680796191;
    5. access_time=0;
    6. owner=root;
    7. group=supergroup;
    8. permission=rwxr-xr-x;
    9. isSymlink=false
    10. }

    2.13 递归查看指定目录下所有文件的信息

    1. @Test
    2. public void listFilesRecursive() throws Exception {
    3. RemoteIterator files = fileSystem.listFiles(new Path("/hbase"), true);
    4. while (files.hasNext()) {
    5. System.out.println(files.next());
    6. }
    7. }

    和上面输出类似,只是多了文本大小,副本系数,块大小信息。

    1. LocatedFileStatus{
    2. path=hdfs://master:8020/hbase/hbase.version;
    3. isDirectory=false;
    4. length=7;
    5. replication=1;
    6. blocksize=134217728;
    7. modification_time=1554129052916;
    8. access_time=1554902661455;
    9. owner=root; group=supergroup;
    10. permission=rw-r--r--;
    11. isSymlink=false}

    2.14 查看文件的块信息

    1. @Test
    2. public void getFileBlockLocations() throws Exception {
    3. FileStatus fileStatus = fileSystem.getFileStatus(new Path("/hdfs-api/test/kafka.tgz"));
    4. BlockLocation[] blocks = fileSystem.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());
    5. for (BlockLocation block : blocks) {
    6. System.out.println(block);
    7. }
    8. }

    块输出信息有三个值,分别是文件的起始偏移量 (offset),文件大小 (length),块所在的主机名 (hosts)。

    0,57028557,hadoop001

    这里我上传的文件只有 57M(小于 128M),且程序中设置了副本系数为 1,所有只有一个块信息。

  • 相关阅读:
    【Python】JSON格式文件处理
    JavaScript中一个优雅的运算符使用技巧
    Android动态更换图标
    基于反向推理的序列预测模型
    OFDM通信系统仿真之交织技术
    JavaScript练手小技巧:我破解了原神官网全屏滚动的秘密
    【QT】ROS2 Humble联合使用QT教程
    change DLL文件名
    【Python爬虫】批量爬取豆瓣电影排行Top250
    防火墙部署模式 -- 镜像流量(旁路模式)
  • 原文地址:https://blog.csdn.net/shangjg03/article/details/133877378