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 相关文章推荐
SpringBoot2 参数管理实践之入参出参与校验的方式
Jun 16 Java/Android
spring项目中切面及AOP的使用方法
Jun 26 Java/Android
利用Java设置Word文本框中的文字旋转方向的实现方法
Jun 28 Java/Android
小程序与后端Java接口交互实现HelloWorld入门
Jul 09 Java/Android
java设计模式--原型模式详解
Jul 21 Java/Android
dubbo集成zipkin获取Traceid的实现
Jul 26 Java/Android
你知道Java Spring的两种事务吗
Mar 16 Java/Android
Java虚拟机内存结构及编码实战分享
Apr 07 Java/Android
Elasticsearch Recovery 详细介绍
Apr 19 Java/Android
Spring Data JPA框架自定义Repository接口
Apr 28 Java/Android
Java 数组的使用
May 11 Java/Android
Java实现HTML转为Word的示例代码
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字符串长度计算 - strlen()函数使用介绍
2013/10/15 PHP
PHP中round()函数对浮点数进行四舍五入的方法
2014/11/19 PHP
php结合ACCESS的跨库查询功能
2015/06/12 PHP
PHP实现图片上传并压缩
2015/12/22 PHP
thinkPHP5.1框架中Request类四种调用方式示例
2019/08/03 PHP
jquery ajax学习笔记2 使用XMLHttpRequest对象的responseXML
2011/10/16 Javascript
Javascript实现重力弹跳拖拽运动效果示例
2013/06/28 Javascript
jquery操作checkbox火狐下第二次无法勾选的解决方法
2016/10/10 Javascript
从零学习node.js之简易的网络爬虫(四)
2017/02/22 Javascript
node作为中间服务层如何发送请求(发送请求的实现方法详解)
2018/01/02 Javascript
Nodejs使用Mongodb存储与提供后端CRD服务详解
2018/09/04 NodeJs
浅谈js闭包理解
2019/04/01 Javascript
Vue this.$router.push(参数)实现页面跳转操作
2020/09/09 Javascript
[02:28]DOTA2英雄基础教程 灰烬之灵
2013/12/19 DOTA
[01:05:07]DOTA2-DPC中国联赛 正赛 DLG vs Dragon BO3 第一场2月1日
2021/03/11 DOTA
Python 实现数据库(SQL)更新脚本的生成方法
2017/07/09 Python
python smtplib模块实现发送邮件带附件sendmail
2018/05/22 Python
Python FTP两个文件夹间的同步实例代码
2018/05/25 Python
为什么str(float)在Python 3中比Python 2返回更多的数字
2018/10/16 Python
postman模拟访问具有Session的post请求方法
2019/07/15 Python
Python学习笔记之字符串和字符串方法实例详解
2019/08/22 Python
Python 字节流,字符串,十六进制相互转换实例(binascii,bytes)
2020/05/11 Python
Python数据库封装实现代码示例解析
2020/09/05 Python
Python新建项目自动添加介绍和utf-8编码的方法
2020/12/26 Python
欧洲著名的珠宝和手表网上商城:uhrcenter
2017/04/10 全球购物
图库照片、免版税图片、矢量艺术、视频片段:Depositphotos
2019/08/02 全球购物
办公室文书岗位职责
2013/12/16 职场文书
幼儿园亲子活动方案
2014/01/29 职场文书
目标管理责任书
2014/04/15 职场文书
文明礼仪伴我行演讲稿
2014/05/12 职场文书
环保标语大全
2014/06/12 职场文书
行政秘书工作自我鉴定
2014/09/15 职场文书
2014年计划生育协会工作总结
2014/11/14 职场文书
2015年学校后勤工作总结
2015/04/08 职场文书
2019年员工旷工保证书!
2019/06/28 职场文书
python 镜像环境搭建总结
2022/09/23 Python