实验环境

  • 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配置

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>

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>

启动hadoop

sbin/start-dfs.sh

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

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

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);
    }
}

运行结果:

编程实现一个类“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");

    }
}

运行结果:

②实现缓存功能,即利用”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内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

利用Java连接Hadoop进行编程的更多相关文章

  1. 使用 Swift语言进行 Hadoop 数据流应用程序开发

    如果您发现了问题,或者希望为改进本文提供意见和建议,请在这里指出.在您开始之前,请参阅目前待解决的问题清单.简介本项目包括两类Hadoop流处理应用程序:映射器mapper和总结器reducer。如上所示,在Hadoop上编写流处理程序是一个很简单的工作,也不需要依赖于特定的软件体系。

  2. NT IIS下用ODBC连接数据库

    $connection=intodbc_connect建立数据库连接,$query_string="查询记录的条件"如:$query_string="select*fromtable"用$cur=intodbc_exec检索数据库,将记录集放入$cur变量中。再用while{$var1=odbc_result;$var2=odbc_result;...}读取odbc_exec()返回的数据集$cur。最后是odbc_close关闭数据库的连接。odbc_result()函数是取当前记录的指定字段值。

  3. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  4. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  5. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  6. Java实现世界上最快的排序算法Timsort的示例代码

    Timsort 是一个混合、稳定的排序算法,简单来说就是归并排序和二分插入排序算法的混合体,号称世界上最好的排序算法。本文将详解Timsort算法是定义与实现,需要的可以参考一下

  7. Java日期工具类的封装详解

    在日常的开发中,我们难免会对日期格式化,对日期进行计算,对日期进行校验,为了避免重复写这些琐碎的逻辑,我这里封装了一个日期工具类,方便以后使用,直接复制代码到项目中即可使用,需要的可以参考一下

  8. Java设计模式之模板方法模式Template Method Pattern详解

    在我们实际开发中,如果一个方法极其复杂时,如果我们将所有的逻辑写在一个方法中,那维护起来就很困难,要替换某些步骤时都要重新写,这样代码的扩展性就很差,当遇到这种情况就要考虑今天的主角——模板方法模式

  9. Java 中 Class Path 和 Package的使用详解

    这篇文章主要介绍了Java 中 Class Path和Package的使用详解,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下

  10. java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源)

    这篇文章主要介绍了java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源),文章围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部