利用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 11 Java/Android
Java输出Hello World完美过程解析
Jun 13 Java/Android
详解Java实现设计模式之责任链模式
Jun 23 Java/Android
使用feign服务调用添加Header参数
Jun 23 Java/Android
小程序与后端Java接口交互实现HelloWorld入门
Jul 09 Java/Android
dubbo服务整合zipkin详解
Jul 26 Java/Android
Spring事务管理下synchronized锁失效问题的解决方法
Mar 31 Java/Android
springboot用户数据修改的详细实现
Apr 06 Java/Android
详细介绍Java中的CyclicBarrier
Apr 13 Java/Android
Android在Sqlite3中的应用及多线程使用数据库的建议
Apr 24 Java/Android
tree shaking对打包体积优化及作用
Jul 07 Java/Android
Android实现获取短信验证码并自动填充
May 21 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
PHP+javascript液晶时钟
2006/10/09 PHP
PHP 在线翻译函数代码
2009/05/07 PHP
linux下为php添加curl扩展的方法
2011/07/29 PHP
PHP管理内存函数 memory_get_usage()使用介绍
2012/09/23 PHP
PHP--用万网的接口实现域名查询功能
2012/12/13 PHP
php页面跳转代码 输入网址跳转到你定义的页面
2013/03/28 PHP
php防止sql注入代码实例
2013/12/18 PHP
PHP mysqli事务操作常用方法分析
2017/07/22 PHP
PHP7新特性之抽象语法树(AST)带来的变化详解
2018/07/17 PHP
ThinkPHP框架结合Ajax实现用户名校验功能示例
2019/07/03 PHP
php 实现银联商务H5支付的示例代码
2019/10/12 PHP
火狐浏览器(firefox)下获得Event对象以及keyCode
2008/11/13 Javascript
使用简洁的jQuery方法实现隔行换色功能
2014/01/02 Javascript
js document.write()使用介绍
2014/02/21 Javascript
jquery选择器需要注意的问题
2014/11/26 Javascript
基于javascript实现彩票随机数生成(简单版)
2020/04/17 Javascript
基于javascript bootstrap实现生日日期联动选择
2016/04/07 Javascript
JavaScript SHA1加密算法实现详细代码
2016/10/06 Javascript
微信小程序 UI与容器组件总结
2017/02/21 Javascript
angular4中关于表单的校验示例
2017/10/16 Javascript
[05:02]2014DOTA2 TI中国区预选赛精彩TOPPLAY第三弹
2014/06/25 DOTA
[43:33]EG vs Spirit Supermajor 败者组 BO3 第一场 6.4
2018/06/05 DOTA
Python的Flask框架中SQLAlchemy使用时的乱码问题解决
2015/11/07 Python
Python编程对列表中字典元素进行排序的方法详解
2017/05/26 Python
python 读取txt,json和hdf5文件的实例
2018/06/05 Python
python opencv鼠标事件实现画框圈定目标获取坐标信息
2020/04/18 Python
python中操作文件的模块的方法总结
2021/02/04 Python
Pytorch实现WGAN用于动漫头像生成
2021/03/04 Python
CSS3 @keyframes简单动画实现
2018/02/24 HTML / CSS
联想阿根廷官方网站:Lenovo Argentina
2019/10/14 全球购物
Ibatis如何调用存储过程
2015/05/15 面试题
Ajax主要包含了哪些技术
2014/06/12 面试题
党的群众路线教育实践活动学习心得体会
2014/03/03 职场文书
单位介绍信格式范文
2015/05/04 职场文书
Python3.8官网文档之类的基础语法阅读
2021/09/04 Python
详细介绍MySQL中limit和offset的用法
2022/05/06 MySQL