java实现对Hadoop的操作


Posted in Java/Android onJuly 01, 2021

基本操作

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;

@RunWith(JUnit4.class)
@DisplayName("Test using junit4")
public class HadoopClientTest {

    private FileSystem fileSystem = null;

    @BeforeEach
    public void init() throws URISyntaxException, IOException, InterruptedException {
        Configuration configuration = new Configuration();

        configuration.set("dfs.replication", "1");
        configuration.set("dfs.blocksize", "64m");
        fileSystem = FileSystem.get(new URI("hdfs://hd-even-01:9000"), configuration, "root");
    }
    /**
     * 从本地复制文件到Hadoop
     *
     * @throws URISyntaxException
     * @throws IOException
     * @throws InterruptedException
     */
    @Test
    public void copyFileFromLocal() throws URISyntaxException, IOException, InterruptedException {
        // 上传文件
        fileSystem.copyFromLocalFile(new Path("C:\\Users\\Administrator\\Desktop\\win10激活.txt"), new Path("/even1"));
        // 关闭流,报错winUtils,因为使用了linux的tar包,如果windows要使用,则需要编译好这个winUtils包才能使用
        fileSystem.close();
    }

    /**
     * 从Hadoop下载文件到本地,下载需要配置Hadoop环境,并添加winutils到bin目录
     *
     * @throws URISyntaxException
     * @throws IOException
     * @throws InterruptedException
     */
    @Test
    public void copyFileToLocal() throws URISyntaxException, IOException, InterruptedException {
        // 下载文件
        fileSystem.copyToLocalFile(new Path("/win10激活.txt"), new Path("E:/"));
        // 关闭流,报错winUtils,因为使用了linux的tar包,如果windows要使用,则需要编译好这个winUtils包才能使用
        fileSystem.close();
    }


    /**
     * 创建文件夹
     *
     * @throws IOException
     */
    @Test
    public void hdfsMkdir() throws IOException {
        // 调用创建文件夹方法
        fileSystem.mkdirs(new Path("/even1"));
        // 关闭方法
        fileSystem.close();
    }

    /**
     * 移动文件/修改文件名
     */
    public void hdfsRename() throws IOException {
        fileSystem.rename(new Path(""), new Path(""));
        fileSystem.close();
    }

    /**
     * 删除文件/文件夹
     *
     * @throws IOException
     */
    @Test
    public void hdfsRm() throws IOException {
//        fileSystem.delete(new Path(""));
        // 第二个参数表示递归删除
        fileSystem.delete(new Path(""), true);

        fileSystem.close();
    }

    /**
     * 查看hdfs指定目录的信息
     *
     * @throws IOException
     */
    @Test
    public void hdfsLs() throws IOException {
        // 调用方法返回远程迭代器,第二个参数是把目录文件夹内的文件也列出来
        RemoteIterator<LocatedFileStatus> listFiles = fileSystem.listFiles(new Path("/"), true);
        while (listFiles.hasNext()) {
            LocatedFileStatus locatedFileStatus = listFiles.next();

            System.out.println("文件路径:" + locatedFileStatus.getPath());
            System.out.println("块大小:" + locatedFileStatus.getBlockSize());
            System.out.println("文件长度:" + locatedFileStatus.getLen());
            System.out.println("副本数量:" + locatedFileStatus.getReplication());
            System.out.println("块信息:" + Arrays.toString(locatedFileStatus.getBlockLocations()));
        }

        fileSystem.close();
    }

    /**
     * 判断是文件还是文件夹
     */
    @Test
    public void findHdfs() throws IOException {
        // 1,展示状态信息
        FileStatus[] listStatus = fileSystem.listStatus(new Path("/"));
        // 2,遍历所有文件
        for (FileStatus fileStatus : listStatus) {
            if (fileStatus.isFile())
                System.out.println("是文件:" + fileStatus.getPath().getName());
            else if (fileStatus.isDirectory())
                System.out.println("是文件夹:" + fileStatus.getPath().getName());
        }

        fileSystem.close();
    }

}

文件读写

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

@RunWith(JUnit4.class)
@DisplayName("this is read write test!")
public class HadoopReadWriteTest {
    FileSystem fileSystem = null;
    Configuration configuration = null;
    @Before
    public void init() throws URISyntaxException, IOException, InterruptedException {
        // 1,加载配置
        configuration = new Configuration();
        // 2,构建客户端
        fileSystem = FileSystem.get(new URI("hdfs://hd-even-01:9000/"), configuration, "root");
    }


    @Test
    public void testReadData() throws IOException {
        // 1,获取hdfs文件流
        FSDataInputStream open = fileSystem.open(new Path("/win10激活.txt"));
        // 2,设置一次获取的大小
        byte[] bytes = new byte[1024];
        // 3,读取数据
        while (open.read(bytes) != -1)
            System.out.println(Arrays.toString(bytes));

        open.close();
        fileSystem.close();
    }

    /**
     * 使用缓存流
     *
     * @throws IOException
     */
    @Test
    public void testReadData1() throws IOException {
        FSDataInputStream open = fileSystem.open(new Path("/win10激活.txt"));

        // 使用缓冲流会快点
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(open, StandardCharsets.UTF_8));

        String line = "";

        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }

        bufferedReader.close();
        open.close();
        fileSystem.close();
    }

    /**
     * 指定偏移量来实现只读部分内容
     */
    @Test
    public void readSomeData() throws IOException {
        FSDataInputStream open = fileSystem.open(new Path("/win10激活.txt"));


        // 指定开始的index
        open.seek(14);

        // 指定读的多少
        byte[] bytes = new byte[5];
        while (open.read(bytes) != -1)
            System.out.println(new String(bytes));

        open.close();
        fileSystem.close();

    }

    /**
     * 流方式写数据
     * @throws IOException
     */
    @Test
    public void writeData() throws IOException {
        // 1,获取输出流
        FSDataOutputStream out = fileSystem.create(new Path("/win11.txt"), false);

        // 2,获取需要写的文件输入流
        FileInputStream in = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\xixi.txt"));

        byte[] b = new byte[1024];
        int read = 0;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
        in.close();
        out.close();
        fileSystem.close();
    }

    /**
     * 直接写字符串
     */
    @Test
    public void writeData1() throws IOException {
        // 1,创建输出流
        FSDataOutputStream out = fileSystem.create(new Path("/aibaobao.txt"), false);
        // 2,写数据
        out.write("wochaoaibaobao".getBytes());
        // 3,关闭流
        IOUtils.closeStream(out);
        fileSystem.close();
    }

    /**
     * IOUtils方式上传
     *
     * @throws IOException
     */
    @Test
    public void putToHdfs() throws IOException {
        // 1,获取输入流
        FileInputStream in = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\xixi.txt"));
        // 2,获取输出流
        FSDataOutputStream out = fileSystem.create(new Path("/haddopPut.txt"), false);
        // 3,拷贝
        IOUtils.copyBytes(in, out, configuration);
        // 4,关闭流
        IOUtils.closeStream(in);
        IOUtils.closeStream(out);
        fileSystem.close();
    }

    /**
     * IOUtils方式下载
     * @throws IOException
     */
    @Test
    public void getFromHdfs() throws IOException {
        // 1,获取输入流
        FSDataInputStream open = fileSystem.open(new Path("/haddopPut.txt"));
        // 2,获取输出流
        FileOutputStream out = new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\haddopPut.txt"));
        // 3,拷贝
        IOUtils.copyBytes(open, out, configuration);
        // 4,关闭流
        IOUtils.closeStream(open);
        IOUtils.closeStream(out);
        fileSystem.close();
    }
}

到此这篇关于java实现对Hadoop的操作的文章就介绍到这了,更多相关Java Hadoop内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Java/Android 相关文章推荐
SpringCloud Alibaba 基本开发框架搭建过程
Jun 13 Java/Android
Java内存模型之happens-before概念详解
Jun 13 Java/Android
解决Maven项目中 Invalid bound statement 无效的绑定问题
Jun 15 Java/Android
springcloud之Feign超时问题的解决
Jun 24 Java/Android
解决ObjectMapper.convertValue() 遇到的一些问题
Jun 30 Java/Android
Java使用httpRequest+Jsoup爬取红蓝球号码
Jul 02 Java/Android
Java8中接口的新特性使用指南
Nov 01 Java/Android
Java实现经典游戏泡泡堂的示例代码
Apr 04 Java/Android
Java数组详细介绍及相关工具类
Apr 14 Java/Android
Java存储没有重复元素的数组
Apr 29 Java/Android
springboot为异步任务规划自定义线程池的实现
Jun 14 Java/Android
java.util.NoSuchElementException原因及两种解决方法
Jun 28 Java/Android
解决MultipartFile.transferTo(dest) 报FileNotFoundExcep的问题
Jul 01 #Java/Android
Java中多线程下载图片并压缩能提高效率吗
分析ZooKeeper分布式锁的实现
Java并发编程必备之Future机制
详解Spring Boot使用系统参数表提升系统的灵活性
Jun 30 #Java/Android
浅谈resultMap的用法及关联结果集映射
Spring中bean的生命周期之getSingleton方法
You might like
深入理解PHP之require/include顺序 推荐
2011/01/02 PHP
PHP去掉从word直接粘贴过来的没有用格式的函数
2012/10/29 PHP
smarty模板引擎之内建函数用法
2015/03/30 PHP
php如何连接sql server
2015/10/16 PHP
php的闭包(Closure)匿名函数初探
2016/02/14 PHP
php自定义中文字符串截取函数substr_for_gb2312及substr_for_utf8示例
2016/05/28 PHP
利用PHP扩展Xhprof分析项目性能实践教程
2018/09/05 PHP
Thinkphp 框架扩展之驱动扩展实例分析
2020/04/27 PHP
php对mongodb的扩展(初识如故)
2012/11/11 Javascript
html向js方法传递参数具体实现
2013/08/08 Javascript
JS获取农历日期具体实例
2013/11/14 Javascript
jQery使网页在显示器上居中显示适用于任何分辨率
2014/06/09 Javascript
JavaScript中实现继承的三种方式和实例
2015/01/29 Javascript
javascript顺序加载图片的方法
2015/07/18 Javascript
如何利用模板将HTML从JavaScript中抽离
2016/10/08 Javascript
JavaScript给每一个li节点绑定点击事件的实现方法
2016/12/01 Javascript
浅谈Javascript中的Label语句
2016/12/14 Javascript
微信小程序实现皮肤功能(夜间模式)
2017/06/18 Javascript
浅谈JavaScript 代码简洁之道
2019/01/09 Javascript
jQuery实现input[type=file]多图预览上传删除等功能
2019/08/02 jQuery
VUEX采坑之路之获取不到$store的解决方法
2019/11/08 Javascript
JavaScript组合模式---引入案例分析
2020/05/23 Javascript
python多重继承新算法C3介绍
2014/09/28 Python
简单的python后台管理程序
2017/04/13 Python
通过Python 接口使用OpenCV的方法
2018/04/02 Python
selenium+python自动化测试之多窗口切换
2019/01/23 Python
Opencv+Python实现图像运动模糊和高斯模糊的示例
2019/04/11 Python
基于Python把网站域名解析成ip地址
2020/05/25 Python
css3个性化字体_动力节点Java学院整理
2017/07/12 HTML / CSS
卡骆驰新加坡官网:Crocs新加坡
2018/06/12 全球购物
30年同学聚会邀请函
2014/01/25 职场文书
小摄影师教学反思
2014/04/27 职场文书
服务理念口号
2014/06/11 职场文书
文秘自荐信
2014/06/28 职场文书
2015年公务员试用期工作总结
2015/05/28 职场文书
MySQL空间数据存储及函数
2021/09/25 MySQL