HDFS Java API操作(IDEA版)

2023-05-16

目标

通过Java API来操作HDFS,完成的操作有:文件上传、文件下载、新建文件夹、查看文件、删除文件。

前提条件

1.Windows下安装好jdk1.8

2.Windows下安装好maven,这里使用Maven3.6.3

3.Windows下安装好IDEA,这里使用IDEA2021

4.Linux下安装好hadoop2,这里使用hadoop2.7.3

操作步骤

1.新建一个Maven工程

打开IDEA-->File-->New-->Project

选择Maven-->点击Next

 选择工程代码存放目录,这个目录需要为一个空目录,目录名称就是工程名称,可以点击Artifact Coordinates左侧的三角形展开内容后,可以修改组织ID,组织ID一般为公司域名的倒写,例如:域名为baidu.com,组织ID填写com.baidu。这里使用默认值。然后点击Finish按钮完成Maven工程的创建。

2.pom.xml添加相关依赖

pom.xml</project>上一行添加如下依赖:

   <dependencies>
        <!-- hadoop相关依赖 -->
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <version>2.7.3</version>
        </dependency>
        <!-- 单元测试依赖 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!-- log4j依赖 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.17.2</version>
        </dependency>
    </dependencies>

 加载依赖

可以看到

3.编写测试代码

新建包

src\test\java目录下新建package,包名为GroupID的值:org.example

新建HdfsTest

新建出的包名处,右键-->New-->Java Class 

 填写类名:HdfsTest

文件上传

将本地D:\test\input\1.txt上传到HDFS的/目录下

在HdfsTest类编写代码,实现文件上传的代码如下:

    /**
     * 测试上传文件
     */
    @Test
    public void upload() throws URISyntaxException {
        Configuration conf = new Configuration();
        URI uri = new URI("hdfs://192.168.193.140:8020");//hdfs服务端地址
        String localDir = "file:///D:/test/input/1.txt";//注意:这里的本地文件是指idea所在系统的本地文件
        String hdfsDir = "/";
        try {
            Path localPath = new Path(localDir);
            Path hdfsPath = new Path(hdfsDir);
            FileSystem fs = FileSystem.get(uri,conf,"hadoop");
            fs.copyFromLocalFile(localPath, hdfsPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

测试前数据准备,在WindowsD:\test\input目录下新建一个1.txt文件,1.txt内容为


hello world
hello hadoop  

启动hdfs服务


start-dfs.sh  

查看HDFS的/目录,没有1.txt文件


[hadoop@node1 ~]$ hdfs dfs -ls /
Found 10 items
-rw-r--r--   1 hadoop supergroup         26 2022-03-14 10:48 /2.txt
-rw-r--r--   1 hadoop supergroup       1028 2022-03-15 16:22 /core-site.xml
drwxr-xr-x   - hadoop supergroup          0 2022-03-14 10:39 /input
-rw-r--r--   3 hadoop supergroup         27 2022-03-16 09:19 /newfile.txt
drwxr-xr-x   - hadoop supergroup          0 2022-03-14 21:40 /out1
drwxr-xr-x   - hadoop supergroup          0 2022-03-18 15:08 /out318
drwxr-xr-x   - hadoop supergroup          0 2022-03-18 15:45 /out318-2
drwxr-xr-x   - hadoop supergroup          0 2022-03-15 11:05 /output
drwxr-xr-x   - hadoop supergroup          0 2022-03-14 10:32 /test
drwx------   - hadoop supergroup          0 2022-03-18 15:45 /tmp
​  

运行测试,点击upload方法左侧的三角形,然后点击Run 'upload()'运行upload方法

 

看到Tests passed 或者 Exit code 0 说明运行成功。

 

查看HDFS的/目录,发现有1.txt文件


[hadoop@node1 ~]$ hdfs dfs -ls /
Found 11 items
-rw-r--r--   3 hadoop supergroup         25 2022-03-21 23:26 /1.txt
-rw-r--r--   1 hadoop supergroup         26 2022-03-14 10:48 /2.txt
-rw-r--r--   1 hadoop supergroup       1028 2022-03-15 16:22 /core-site.xml
drwxr-xr-x   - hadoop supergroup          0 2022-03-14 10:39 /input
-rw-r--r--   3 hadoop supergroup         27 2022-03-16 09:19 /newfile.txt
drwxr-xr-x   - hadoop supergroup          0 2022-03-14 21:40 /out1
drwxr-xr-x   - hadoop supergroup          0 2022-03-18 15:08 /out318
drwxr-xr-x   - hadoop supergroup          0 2022-03-18 15:45 /out318-2
drwxr-xr-x   - hadoop supergroup          0 2022-03-15 11:05 /output
drwxr-xr-x   - hadoop supergroup          0 2022-03-14 10:32 /test
drwx------   - hadoop supergroup          0 2022-03-18 15:45 /tmp  

查看1.txt文件内容


[hadoop@node1 ~]$ hdfs dfs -cat /1.txt
hello world
hello hadoop  

至此,说明从文件上传成功了。

思考:程序是如何实现文件上传的,核心代码是什么?如果不使用api是否可以自定义实现上传功能的代码?

文件下载

将HDFS /1.txt下载到本地D:\test目录下

	/**
     * 测试下载文件
     */
    @Test
    public void download(){
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://192.168.193.140:8020");
        String localDir = "D:\\test\\download";//IDEA在windows下,所以本地是windows系统
        String hdfsDir = "/1.txt";//下载文件
        try {
            Path localPath = new Path(localDir);
            Path hdfsPath = new Path(hdfsDir);
            FileSystem fs = FileSystem.newInstance(conf);
            fs.copyToLocalFile(hdfsPath, localPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 运行测试

查看本地是否成功下载了1.txt文件

新建文件夹

    /**
     * 新建文件夹
     */
    @Test
    public void mkdir() throws URISyntaxException {
        Configuration conf = new Configuration();
        URI uri = new URI("hdfs://192.168.193.140:8020");
        String hdfsDir = "/mkdir_test";
        Path path = new Path(hdfsDir);
        try {
            FileSystem fs = FileSystem.get(uri,conf,"hadoop");
            fs.mkdirs(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 运行测试

查看HDFS 是否创建了/mkdir_test

[hadoop@node1 ~]$ hdfs dfs -ls /
Found 12 items
-rw-r--r--   3 hadoop supergroup         25 2022-03-21 23:26 /1.txt
-rw-r--r--   1 hadoop supergroup         26 2022-03-14 10:48 /2.txt
-rw-r--r--   1 hadoop supergroup       1028 2022-03-15 16:22 /core-site.xml
drwxr-xr-x   - hadoop supergroup          0 2022-03-14 10:39 /input
drwxr-xr-x   - hadoop supergroup          0 2022-03-21 23:51 /mkdir_test
-rw-r--r--   3 hadoop supergroup         27 2022-03-16 09:19 /newfile.txt
drwxr-xr-x   - hadoop supergroup          0 2022-03-14 21:40 /out1
drwxr-xr-x   - hadoop supergroup          0 2022-03-18 15:08 /out318
drwxr-xr-x   - hadoop supergroup          0 2022-03-18 15:45 /out318-2
drwxr-xr-x   - hadoop supergroup          0 2022-03-15 11:05 /output
drwxr-xr-x   - hadoop supergroup          0 2022-03-14 10:32 /test
drwx------   - hadoop supergroup          0 2022-03-18 15:45 /tmp

 

思考:程序是如何实现文件下载的,核心代码是什么?如果不使用api是否可以自定义实现下载功能的代码?

查看文件状态

查看HDFS已存在的目录下的文件和目录,本案例查看的是/user,如果没有/user目录需要自行创建

	/**
     * 查看文件状态
     */
    @Test
    public void listFiles(){
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://192.168.193.140:8020");
        try {
            FileSystem fs = FileSystem.newInstance(conf);
            // listFiles递归查询所有目录和文件
            RemoteIterator<LocatedFileStatus> iterator = fs.listFiles(new Path("/user"), true);
            while (iterator.hasNext()){
                LocatedFileStatus next = iterator.next();
                System.out.println(next.getPath());
            }

            System.out.println("===================");

            // listStatus只查询当前目录下的目录和文件
            FileStatus[] fileStatuses = fs.listStatus(new Path("/user"));
            for (int i = 0; i < fileStatuses.length; i++) {
                FileStatus fileStatus = fileStatuses[i];
                System.out.println(fileStatus.getPath());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 思考:这个程序能否运行成功,如果不能运行成功,原因是什么?请自行修改代码并运行成功。

删除文件

	/**
     * 删除目录或文件
     */
    @Test
    public void delete() throws URISyntaxException {
        Configuration conf = new Configuration();
        URI uri = new URI("hdfs://192.168.193.140:8020");
        String hdfsDir = "/mkdir_test";
        try {
            FileSystem fs = FileSystem.get(uri,conf,"hadoop");
            Path hdfsPath = new Path(hdfsDir);
            fs.delete(hdfsPath,true);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

扩展

使用流拷贝方式实现上传和下载

    // 采用流拷贝的方式实现上传、下载

    /**
     * 上传
     */
    @Test
    public void uploadByIOStream() throws URISyntaxException {
        Configuration conf = new Configuration();
        URI uri = new URI("hdfs://192.168.193.140:8020");
        try {
            FileSystem fs = FileSystem.get(uri, conf, "hadoop");
            FileInputStream is = new FileInputStream("d:\\test\\data.txt");
            FSDataOutputStream os = fs.create(new Path("/input2/data.txt"));//创建一个路径
            // 流拷贝
            IOUtils.copyBytes(is, os, 1024);

            // 关闭资源
            is.close();
            os.close();
            fs.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    /**
     * 下载
     */
    @Test
    public void downloadByIOStream() throws URISyntaxException, IOException, InterruptedException {
        Configuration conf = new Configuration();
        URI uri = new URI("hdfs://192.168.193.140:8020");
        FileSystem fs = FileSystem.get(uri, conf, "hadoop");

        FSDataInputStream is = fs.open(new Path("/input2/1.txt"));//输入流
        FileOutputStream os = new FileOutputStream("d:\\test\\1downbyio.txt");

        IOUtils.copyBytes(is,os,1024);

        is.close();
        os.close();
        fs.close();

    }

完成!enjoy it!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HDFS Java API操作(IDEA版) 的相关文章

  • HashMap不写入数据库

    我尝试在我的数据库中写入 但只写入发件人和消息 我不明白为什么会发生这种情况 我认为问题出在我使用 sendMessage 的地方 我认为问题是我没有什么可以做的读 写其他用户的主键 我在数据库中写入消息的活动 public class M
  • 使用 GWT CellTableBuilder 构建树表

    Is it possible to build a tree table like this http www sencha com examples ExamplePlace basictreegrid with the new Cell
  • 如果在睡眠线程上调用interrupt()会发生什么?

    我有一个线程 然后run I call sleep 如果我中断这个线程会发生什么 MyThread extends Thread public void run try sleep 1000000 catch InterruptedExce
  • Grails 2.3.0 自动重新加载不起作用

    我最近将我们的项目升级到 grails 2 3 0 一切工作正常 除了每当我更改代码时自动重新加载都无法工作的问题 这包括所有项目工件 控制器 域 服务 gsps css 和 javascript 文件 我的旧版本 grails 可以正常工
  • Spring安全“记住我”cookie在第一个请求中不可用

    我无法在登录请求后检索 Spring 记住我 cookie 但它在对受保护页面的下一个请求中工作正常 谁能告诉我怎样才能立即得到它 我在登录请求中设置了记住我的 cookie 但在 Spring 重定向回原始 受保护的 url 后无法检索它
  • eclipse中导入项目文件夹图标

    我在 Eclipse 工作区中新导入的 Maven 项目有J and M项目文件夹顶部的图标 项目和包资源管理器 而其他导入的 Maven 项目只有一个J icon 有人可以解释其中的区别吗 该项目有J装饰器被称为 Java 项目和具有M装
  • 在 HTTP 标头中发送 UTF-8 值会导致 Mojibake

    我想使用 servlet 发送阿拉伯语数据HTTPServletResponse给客户 我正在尝试这个 response setCharacterEncoding UTF 8 response setHeader Info arabicWo
  • Java 8 中函数式接口的使用

    这是来自的后续问题Java 8 中的 双冒号 运算符 https stackoverflow com questions 20001427 double colon operator in java 8其中 Java 允许您使用以下方式引用
  • 如何将 Jfreechart(饼图)添加到 netbeans 的面板中

    我正在使用 netbeans gui 编辑器 并且正在尝试添加一个本身位于内部框架中的 Jfreechart 并且这个内部框架我想将其添加到面板中 正如您在此图中看到的那样 抱歉 我无法直接发布图像 因为我新手 http www flick
  • 获取给定类文件的目录路径

    我遇到的代码尝试从类本身的 class 文件所在的同一目录中读取一些配置文件 File configFiles new File this getClass getResource getPath listFiles new Filenam
  • Java - 返回值是否会中断循环?

    我正在编写一些基本上遵循以下格式的代码 public static boolean isIncluded E element Node
  • Spring Security OAuth2简单配置

    我有一个简单的项目 需要以下简单的配置 我有一个 密码 grant type 这意味着我可以提交用户名 密码 用户在登录表单中输入 并在成功时获得 access token 有了该 access token 我就可以请求 API 并获取用户
  • Dispatcher-servlet 无法映射到 websocket 请求

    我正在开发一个以Spring为主要框架的Java web应用程序 特别使用Spring core Spring mvc Spring security Spring data Spring websocket 像这样在 Spring 上下文
  • 如何在 Eclipse Java 动态 Web 项目中使用 .properties 文件?

    我正在 Eclipse 中开发动态 Web 项目 我创建了一个 properties 文件来存储数据库详细信息 用户名 密码等 我通过右键单击项目和 New gt File 添加它 我使用了Java util包Properties类 但它不
  • 尝试使用等于“是”或“否”的字符串变量重新启动 do-while 循环

    计算行程距离的非常简单的程序 一周前刚刚开始 我有这个循环用于解决真或假问题 但我希望它适用于简单的 是 或 否 我为此分配的字符串是答案 public class Main public static void main String a
  • 对象锁定私有类成员 - 最佳实践? (爪哇)

    I asked 类似的问题 https stackoverflow com questions 10548066 multiple object locks in java前几天 但对回复不满意 主要是因为我提供的代码存在一些人们关注的问题
  • 如何在 Quartz 调度程序中每 25 秒运行一次?

    我正在使用 Java 的 Quartz Scheduling API 你能帮我使用 cron 表达式每 25 秒运行一次吗 这只是一个延迟 它不必总是从第 0 秒开始 例如 序列如下 0 00 0 25 0 50 1 15 1 40 2 0
  • Java:多线程内的 XA 事务传播

    我如何使用事务管理器 例如Bitronix http docs codehaus org display BTM Home JBoss TS http www jboss org jbosstm or Atomikos http www a
  • 在android中跟踪FTP上传数据?

    我有一个运行 Android 的 FTP 系统 但我希望能够在上传时跟踪字节 这样我就可以在上传过程中更新进度条 安卓可以实现这个功能吗 现在 我正在使用org apache common net ftp我正在使用的代码如下 另外 我在 A
  • JAXB - 列表<可序列化>?

    我使用 xjc 制作了一些课程 public class MyType XmlElementRefs XmlElementRef name MyInnerType type JAXBElement class required false

随机推荐

  • 【SandQuant 量化投资】威廉·夏普:资本资产定价:风险条件下的市场均衡理论

    资本资产定价 xff1a 风险条件下的市场均衡理论 I 效用函数 机会曲线与无风险利率II 资本市场均衡III 资本资产定价与系统性风险 威廉 夏普在1964年基于均值方差准则 xff0c 将资产组合理论拓展到了风险条件下资本资产价格的市场
  • 【SandQuant 开源工具】 TradeTime 灵活操作交易日历的python库

    TradeTime TradeTime是针对交易开发的日期时间工具 xff0c 在计算上和python标准库datetime完美结合 xff0c 可以灵活对日期时间进行运算操作 支持和datetime结合使用 xff1b 目前只支持A股交易
  • 分享一个python有趣的freegames库

    freegames xff0c 一个简单的小游戏库 之前在一篇公众号推文看到一个好玩的库 xff0c 就是freegames 1 第一步 xff1a pip install freegames 2 第二步 xff1a python m fr
  • 修改本地仓库,Local Repository无法改变

    问题 xff1a 修改本地仓库的settings xml文件后 xff0c Local Repository无法改变 解决 xff1a 1 xff0c cmd gt mvn v 进行查看maven是否正确安装 2 xff0c setting
  • 虚拟机出现command XXX is available in /bin/ls问题

    问题 xff1a 使用本地的shell命令时候 The command could not be located because 39 usr bin bin 39 is not included in the PATH environme
  • 科大讯飞2022届春招补录内推开启

    xff01 xff01 xff01 科大讯飞2022届春招补录内推开启 xff01 xff01 xff01 内推岗位 xff1a 内推对象 xff1a 招聘流程 xff1a 投递方式 xff1a Step1 内推码 xff1a zyxie6
  • Django中select_related的作用和用法

    在数据库有外键的时候 xff0c 使用 select related 和 prefetch related 可以很好的减少数据库请求的次数 xff0c 从而提高性能 本文通过一个简单的例子详解这两个函数的作用 虽然QuerySet的文档中已
  • 由浅入深掌握Python多线程原理与编程步骤

    由浅入深掌握Python多线程编程 一 Python多线程编程原理1 什么是线程2 线程工作原理3 Python全局锁与线程关系4 Python 支持多线程的模块 二 由简单的示例初步了解多线程编程步骤三 标准库 threading 模块介
  • element-ui如何在表格中插入图片

    第一种 xff1a span class token operator lt span el span class token operator span table span class token operator span colum
  • Cannot find module node-sass解决

    过假期想着在家跑下项目 xff0c 写下代码 xff0c 结果把代码拉下来之后 xff0c 就死活跑不起来了 xff0c 以为是自己电脑node版本的原因 xff0c 结果卸载了node安装了最新版本的 xff0c 结果npm run de
  • element-ui表格中复选框只能选中一个

    代码 xff1a span class token operator lt span el span class token operator span table ref span class token operator 61 span
  • python操作鼠标进行点击

    python中的pyautogui库可以操作鼠标 安装 xff1a pip install pyautogui span class token keyword import span time span class token keywo
  • go中的bcrypt加密

    1 bcrypt是不可逆的加密算法 xff0c 无法通过解密密文得到明文 2 bcrypt和其他对称或非对称加密方式不同的是 xff0c 不是直接解密得到明文 xff0c 也不是二次加密比较密文 xff0c 而是把明文和存储的密文一块运算得
  • go gRPC 服务端推送给客户端流demo

    具体文件目录看上一篇的grpc xff0c 这个demo演示的是服务端以流的形式推送给客户端 pb hello proto syntax span class token operator 61 span span class token
  • docker常用命令

    打包镜像 docker build span class token operator span t demo v1 span class token punctuation span 运行镜像 docker run span class
  • docker镜像加载原理

    docker的镜像实际上是由一层一层的文件系统组成 xff0c 这种层级的文件系统叫做UnionFS bootfs boot file system 主要包含bootloade和kernel xff0c bootloader主要是引导加载k
  • docker网络

    docker network常见的四种模式 桥接模式 bridge xff1a 为每一个容器分配 设置ip等 xff0c 并将容器连接到一个叫做docker0的虚拟网桥 xff0c docker网络默认为该模式 xff0c 使用 netwo
  • 玩客云刷armbian更新源报错The repository ‘http://apt.armbian.com stretch Release‘ does not have a Release file

    玩客云刷armbian系统更新源报错的解决方法 xff08 E The repository 39 http apt armbian com stretch Release 39 does not have a Release file x
  • GPT-4工具是软件工程师工作效率的倍增器

    1 xff0c 你现在正在哪个领域学习或工作呢 xff1f 你用过哪些AI智能工具 xff1f 主要从事AI算法数据集处理 xff0c 模型部署工具开发 xff0c 以及低代码工具开发 使用 Github的 Copilot 编程伴侣超过1个
  • HDFS Java API操作(IDEA版)

    目标 通过Java API来操作HDFS xff0c 完成的操作有 xff1a 文件上传 文件下载 新建文件夹 查看文件 删除文件 前提条件 1 Windows下安装好jdk1 8 2 Windows下安装好maven xff0c 这里使用