利用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 相关文章推荐
MybatisPlus代码生成器的使用方法详解
Jun 13 Java/Android
解析Java中的static关键字
Jun 14 Java/Android
分析ZooKeeper分布式锁的实现
Jun 30 Java/Android
Java使用httpRequest+Jsoup爬取红蓝球号码
Jul 02 Java/Android
Java使用jmeter进行压力测试
Jul 09 Java/Android
java固定大小队列的几种实现方式详解
Jul 15 Java/Android
Java Socket实现多人聊天系统
Jul 15 Java/Android
springboot中rabbitmq实现消息可靠性机制详解
Sep 25 Java/Android
深入解读Java三大集合之map list set的用法
Nov 11 Java/Android
springboot入门 之profile设置方式
Apr 04 Java/Android
Java数组详细介绍及相关工具类
Apr 14 Java/Android
Spring Data JPA框架自定义Repository接口
Apr 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
PHP Curl多线程原理实例详解
2013/11/06 PHP
php实现的Cookies操作类实例
2014/09/24 PHP
PHP实现导出excel数据的类库用法示例
2016/10/15 PHP
PHP实现的DES加密解密封装类完整实例
2017/04/29 PHP
php探针不显示内存解决方法
2019/09/17 PHP
Yii 框架使用数据库(databases)的方法示例
2020/05/19 PHP
JQuery与JSon实现的无刷新分页代码
2011/09/13 Javascript
『jQuery』取指定url格式及分割函数应用
2013/04/22 Javascript
js控制input输入字符解析
2013/12/27 Javascript
jQuery.lazyload+masonry改良图片瀑布流代码
2014/06/20 Javascript
js在IE与firefox的差异集锦
2014/11/11 Javascript
javascript 原型链维护和继承详解
2014/11/26 Javascript
jQuery实现按钮只点击一次后就取消点击事件绑定的方法
2015/06/26 Javascript
JS+CSS实现鼠标滑过时动态翻滚的导航条效果
2015/09/24 Javascript
Bootstrap基本模板的使用和理解1
2016/12/14 Javascript
canvas 画布在主流浏览器中的尺寸限制详细介绍
2016/12/15 Javascript
详解webpack性能优化——DLL
2017/10/20 Javascript
详解如何创建并发布一个 vue 组件
2018/11/08 Javascript
vue项目移动端实现ip输入框问题
2019/03/19 Javascript
微信小程序button标签open-type属性原理解析
2020/01/21 Javascript
Python面向对象编程中关于类和方法的学习笔记
2016/06/30 Python
Python简单实现控制电脑的方法
2018/01/22 Python
用python解压分析jar包实例
2020/01/16 Python
python+requests接口自动化框架的实现
2020/08/31 Python
HTML5 Geolocation API的正确使用方法
2018/12/04 HTML / CSS
html如何对span设置宽度
2019/10/30 HTML / CSS
如何选择使用结构还是类
2014/05/30 面试题
大学生学习生活的自我评价
2013/11/01 职场文书
工作保证书范文
2014/04/29 职场文书
机电专业求职信
2014/06/14 职场文书
道德模范事迹材料
2014/12/20 职场文书
违纪检讨书范文
2015/01/27 职场文书
幼儿园大班个人总结
2015/02/28 职场文书
关于军训的感想
2015/08/07 职场文书
Django显示可视化图表的实践
2021/05/10 Python
Java方法重载和方法重写的区别到底在哪?
2021/06/11 Java/Android