利用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 相关文章推荐
springboot中一些比较常用的注解总结
Jun 11 Java/Android
Java 将PPT幻灯片转为HTML文件的实现思路
Jun 11 Java/Android
解析Java中的static关键字
Jun 14 Java/Android
浅谈spring boot使用thymeleaf版本的问题
Aug 04 Java/Android
logback如何自定义日志存储
Aug 30 Java/Android
MyBatis-Plus 批量插入数据的操作方法
Sep 25 Java/Android
Java实现房屋出租系统详解
Oct 05 Java/Android
RestTemplate如何通过HTTP Basic Auth认证示例说明
Mar 17 Java/Android
Android存储中最基本的文件存储方式
Apr 30 Java/Android
JAVA springCloud项目搭建流程
May 11 Java/Android
Spring Boot优化后启动速度快到飞起技巧示例
Jul 23 Java/Android
Java代码规范与质量检测插件SonarLint的使用
Aug 05 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代码简化
2010/02/08 PHP
php中定义网站根目录的常用方法
2010/08/08 PHP
PHP中Socket连接及读写数据超时问题分析
2016/07/19 PHP
php使用curl_init()和curl_multi_init()多线程的速度比较详解
2018/08/15 PHP
Laravel配合jwt使用的方法实例
2020/10/25 PHP
JQuery 简便实现页面元素数据验证功能
2007/03/24 Javascript
高性能web开发 如何加载JS,JS应该放在什么位置?
2010/05/14 Javascript
js实现简单登录功能的实例代码
2013/11/09 Javascript
Jquery getJSON方法详细分析
2013/12/26 Javascript
Firefox中使用outerHTML的2种解决方法
2014/06/07 Javascript
JS实现的用来对比两个用指定分隔符分割的字符串是否相同
2014/09/19 Javascript
jQuery添加和删除指定标签的方法
2015/12/16 Javascript
Bootstrap 折叠(Collapse)插件用法实例详解
2016/06/01 Javascript
JS实现用户注册时获取短信验证码和倒计时功能
2016/10/27 Javascript
Nodejs进阶:如何将图片转成datauri嵌入到网页中去实例
2016/11/21 NodeJs
js 监控iframe URL的变化实例代码
2017/07/12 Javascript
AngularJS路由删除#符号解决的办法
2017/09/28 Javascript
javaScript中&quot;==&quot;和&quot;===&quot;的区别详解
2018/03/16 Javascript
vue生命周期与钩子函数简单示例
2019/03/13 Javascript
python中Flask框架简单入门实例
2015/03/21 Python
python创建关联数组(字典)的方法
2015/05/04 Python
python根据京东商品url获取产品价格
2015/08/09 Python
python遍历一个目录,输出所有的文件名的实例
2018/04/23 Python
python3 selenium 切换窗口的几种方法小结
2018/05/21 Python
python 划分数据集为训练集和测试集的方法
2018/12/11 Python
Python除法之传统除法、Floor除法及真除法实例详解
2019/05/23 Python
python实现mask矩阵示例(根据列表所给元素)
2020/07/30 Python
matplotlib 范围选区(SpanSelector)的使用
2021/02/24 Python
html5构建触屏网站之网站尺寸探讨
2013/01/07 HTML / CSS
FC-Moto丹麦:欧洲最大的摩托车服装和头盔商店之一
2019/08/20 全球购物
美国围栏公司:Walpole Outdoors
2019/11/19 全球购物
美国饼干礼物和美食甜点购买网站:Cheryl’s
2020/05/28 全球购物
介绍一下RMI的基本概念
2016/12/17 面试题
“5.12”护士节主持词
2015/07/04 职场文书
关于国庆节的广播稿
2015/08/19 职场文书
2019大学竞选班长发言稿
2019/06/27 职场文书