利用Java连接Hadoop进行编程


Posted in Java/Android onJune 28, 2022

实验环境

  • hadoop版本:3.3.2
  • jdk版本:1.8
  • hadoop安装系统:ubuntu18.04
  • 编程环境:IDEA
  • 编程主机:windows

实验内容

测试Java远程连接hadoop

创建maven工程,引入以下依赖:

<dependency>
                <groupId>org.testng</groupId>
                <artifactId>testng</artifactId>
                <version>RELEASE</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-common</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-hdfs</artifactId>
                <version>3.3.2</version>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-common</artifactId>
                <version>3.3.2</version>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-core</artifactId>
                <version>1.2.1</version>
            </dependency>

虚拟机的/etc/hosts配置

利用Java连接Hadoop进行编程

hdfs-site.xml配置

<configuration>
        <property>
                <name>dfs.replication</name>
                <value>1</value>
        </property>
        <property>
                <name>dfs.namenode.name.dir</name>
                <value>file:/root/rDesk/hadoop-3.3.2/tmp/dfs/name</value>
        </property>
        <property>
                <name>dfs.datanode.http.address</name>
                <value>VM-12-11-ubuntu:50010</value>
        </property>
        <property>
                <name>dfs.client.use.datanode.hostname</name>
                <value>true</value>
        </property>
        <property>
                <name>dfs.datanode.data.dir</name>
                <value>file:/root/rDesk/hadoop-3.3.2/tmp/dfs/data</value>
        </property>
</configuration>

利用Java连接Hadoop进行编程

core-site.xml配置

<configuration>
  <property>
          <name>hadoop.tmp.dir</name>
          <value>file:/root/rDesk/hadoop-3.3.2/tmp</value>
          <description>Abase for other temporary directories.</description>
  </property>
  <property>
          <name>fs.defaultFS</name>
          <value>hdfs://VM-12-11-ubuntu:9000</value>
  </property>
</configuration>

利用Java连接Hadoop进行编程

启动hadoop

sbin/start-dfs.sh

主机的hosts(C:\Windows\System32\drivers\etc)文件配置

利用Java连接Hadoop进行编程

尝试连接到虚拟机的hadoop并读取文件内容,这里我读取hdfs下的/root/iinput文件内容

利用Java连接Hadoop进行编程

Java代码:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DistributedFileSystem;
public class TestConnectHadoop {
    public static void main(String[] args) throws Exception {

        String hostname = "VM-12-11-ubuntu";
        String HDFS_PATH = "hdfs://" + hostname + ":9000";
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", HDFS_PATH);
        conf.set("fs.hdfs.impl", DistributedFileSystem.class.getName());
        conf.set("dfs.client.use.datanode.hostname", "true");

        FileSystem fs = FileSystem.get(conf);
        FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
        for (FileStatus fileStatus : fileStatuses) {
            System.out.println(fileStatus.toString());
        }
        FileStatus fileStatus = fs.getFileStatus(new Path("/root/iinput"));
        System.out.println(fileStatus.getOwner());
        System.out.println(fileStatus.getGroup());

        System.out.println(fileStatus.getPath());
        FSDataInputStream open = fs.open(fileStatus.getPath());
        byte[] buf = new byte[1024];
        int n = -1;
        StringBuilder sb = new StringBuilder();
        while ((n = open.read(buf)) > 0) {
            sb.append(new String(buf, 0, n));
        }
        System.out.println(sb);
    }
}

运行结果:

利用Java连接Hadoop进行编程

编程实现一个类“MyFSDataInputStream”,该类继承“org.apache.hadoop.fs.FSDataInputStream",要求如下: ①实现按行读取HDFS中指定文件的方法”readLine()“,如果读到文件末尾,则返回为空,否则返回文件一行的文本

思路:emmm我的思路比较简单,只适用于该要求,仅作参考。
将所有的数据读取出来存储起来,然后根据换行符进行拆分,将拆分的字符串数组存储起来,用于readline返回

Java代码

import org.apache.hadoop.fs.FSDataInputStream;
import java.io.IOException;
import java.io.InputStream;
public class MyFSDataInputStream extends FSDataInputStream {
    private String data = null;
    private String[] lines = null;
    private int count = 0;
    private FSDataInputStream in;
    public MyFSDataInputStream(InputStream in) throws IOException {
        super(in);
        this.in = (FSDataInputStream) in;
        init();
    }
    private void init() throws IOException {
        byte[] buf = new byte[1024];
        int n = -1;
        StringBuilder sb = new StringBuilder();
        while ((n = this.in.read(buf)) > 0) {
            sb.append(new String(buf, 0, n));
        }
        data = sb.toString();
        lines = data.split("\n");
    }
    /**
     * 实现按行读取HDFS中指定文件的方法”readLine()“,如果读到文件末尾,则返回为空,否则返回文件一行的文本
     */
    public String read_line() {
        return count < lines.length ? lines[count++] : null;
    }

}

测试类:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DistributedFileSystem;
public class TestConnectHadoop {
    public static void main(String[] args) throws Exception {

        String hostname = "VM-12-11-ubuntu";
        String HDFS_PATH = "hdfs://" + hostname + ":9000";
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", HDFS_PATH);
        conf.set("fs.hdfs.impl", DistributedFileSystem.class.getName());
        conf.set("dfs.client.use.datanode.hostname", "true");
        FileSystem fs = FileSystem.get(conf);
        FileStatus fileStatus = fs.getFileStatus(new Path("/root/iinput"));
        System.out.println(fileStatus.getOwner());
        System.out.println(fileStatus.getGroup());
        System.out.println(fileStatus.getPath());
        FSDataInputStream open = fs.open(fileStatus.getPath());
        MyFSDataInputStream myFSDataInputStream = new MyFSDataInputStream(open);
        String line = null;
        int count = 0;
        while ((line = myFSDataInputStream.read_line()) != null ) {
            System.out.printf("line %d is: %s\n", count++, line);
        }
        System.out.println("end");

    }
}

运行结果:

利用Java连接Hadoop进行编程

②实现缓存功能,即利用”MyFSDataInputStream“读取若干字节数据时,首先查找缓存,如果缓存中有所需要数据,则直接由缓存提供,否则从HDFS中读取数据

import org.apache.hadoop.fs.FSDataInputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
public class MyFSDataInputStream extends FSDataInputStream {
    private BufferedInputStream buffer;
    private String[] lines = null;
    private int count = 0;
    private FSDataInputStream in;
    public MyFSDataInputStream(InputStream in) throws IOException {
        super(in);
        this.in = (FSDataInputStream) in;
        init();
    }
    private void init() throws IOException {
        byte[] buf = new byte[1024];
        int n = -1;
        StringBuilder sb = new StringBuilder();
        while ((n = this.in.read(buf)) > 0) {
            sb.append(new String(buf, 0, n));
        }
        //缓存数据读取
        buffer = new BufferedInputStream(this.in);
        lines = sb.toString().split("\n");
    }
    /**
     * 实现按行读取HDFS中指定文件的方法”readLine()“,如果读到文件末尾,则返回为空,否则返回文件一行的文本
     */
    public String read_line() {
        return count < lines.length ? lines[count++] : null;
    }
    @Override
    public int read() throws IOException {
        return this.buffer.read();
    }
    public int readWithBuf(byte[] buf, int offset, int len) throws IOException {
        return this.buffer.read(buf, offset, len);
    }
    public int readWithBuf(byte[] buf) throws IOException {
        return this.buffer.read(buf);
    }
}

到此这篇关于利用Java连接Hadoop进行编程的文章就介绍到这了,更多相关Java连接Hadoop内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!


Tags in this post...

Java/Android 相关文章推荐
Java数据结构之链表相关知识总结
Jun 18 Java/Android
java中重写父类方法加不加@Override详解
Jun 21 Java/Android
SpringRetry重试框架的具体使用
Jul 25 Java/Android
SpringMVC 整合SSM框架详解
Aug 30 Java/Android
SpringCloud Feign请求头删除修改的操作代码
Mar 20 Java/Android
Java虚拟机内存结构及编码实战分享
Apr 07 Java/Android
Java详细解析==和equals的区别
Apr 07 Java/Android
Android Studio实现简易进制转换计算器
May 20 Java/Android
Android Studio 计算器开发
May 20 Java/Android
Android中View.post和Handler.post的关系
Jun 05 Java/Android
springboot集成redis存对象乱码的问题及解决
Jun 16 Java/Android
Java多线程并发FutureTask使用详解
Jun 28 Java/Android
SpringBoot项目部署到阿里云服务器的实现步骤
Jun 28 #Java/Android
Java多线程并发FutureTask使用详解
java.util.NoSuchElementException原因及两种解决方法
Jun 28 #Java/Android
Java实现HTML转为Word的示例代码
Jun 28 #Java/Android
Android实现图片九宫格
springboot 全局异常处理和统一响应对象的处理方式
Jun 28 #Java/Android
详解Spring Security如何在权限中使用通配符
Jun 28 #Java/Android
You might like
咖啡冲泡指南 咖啡有哪些制作方式 单品咖啡 意式咖啡
2021/03/06 冲泡冲煮
PHP 的几个配置文件函数
2006/12/21 PHP
php中heredoc与nowdoc介绍
2014/12/25 PHP
PHP中new static()与new self()的比较
2016/08/19 PHP
[原创]php实现数组按拼音顺序排序的方法
2017/05/03 PHP
关于ThinkPHP中的异常处理详解
2018/05/11 PHP
PHP验证类的封装与使用方法详解
2019/01/10 PHP
Function.prototype.bind用法示例
2013/09/16 Javascript
浅析JavaScript中的typeof运算符
2013/11/30 Javascript
基于JavaScript实现通用tab选项卡(通用性强)
2016/01/07 Javascript
jQuery多级联动下拉插件chained用法示例
2016/08/20 Javascript
微信小程序 欢迎页面的制作(源码下载)
2017/01/09 Javascript
JS获取当前时间的实例代码(昨天、今天、明天)
2018/11/13 Javascript
laydate时间日历插件使用方法详解
2018/11/14 Javascript
JavaScript实现轮播图效果
2020/10/30 Javascript
[00:10]神之谴戒
2019/03/06 DOTA
[01:42]DOTA2 – 虚无之灵
2019/08/25 DOTA
用Python写的图片蜘蛛人代码
2012/08/27 Python
python定时检查启动某个exe程序适合检测exe是否挂了
2013/01/21 Python
详谈Python基础之内置函数和递归
2017/06/21 Python
Python中浅拷贝copy与深拷贝deepcopy的简单理解
2018/10/26 Python
Python虚拟环境的原理及使用详解
2019/07/02 Python
django 使用 PIL 压缩图片的例子
2019/08/16 Python
Django admin禁用编辑链接和添加删除操作详解
2019/11/15 Python
Python 绘制可视化折线图
2020/07/22 Python
修复iPhone的safari浏览器上submit按钮圆角bug
2012/12/24 HTML / CSS
俄罗斯宠物用品网上商店:ZooMag
2019/12/12 全球购物
爱国卫生月实施方案
2014/02/21 职场文书
公证书标准格式
2014/04/10 职场文书
供用电专业求职信
2014/07/07 职场文书
办公室文员工作自我鉴定
2014/09/19 职场文书
乡镇党建工作汇报材料
2014/10/27 职场文书
开工典礼致辞
2015/07/29 职场文书
PyTorch梯度裁剪避免训练loss nan的操作
2021/05/24 Python
Oracle11g r2 卸载干净重装的详细教程(亲测有效已重装过)
2021/06/04 Oracle
Hive日期格式转换方法总结
2022/06/25 数据库