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 相关文章推荐
详解Java实践之适配器模式
Jun 18 Java/Android
eclipse创建项目没有dynamic web的解决方法
Jun 24 Java/Android
Java数组与堆栈相关知识总结
Jun 29 Java/Android
Java设计模式之享元模式示例详解
Mar 03 Java/Android
Spring Bean是如何初始化的详解
Mar 22 Java/Android
springboot应用服务启动事件的监听实现
Apr 06 Java/Android
Android Rxjava3 使用场景详解
Apr 07 Java/Android
解决springboot druid数据库连接失败后一直重连的方法
Apr 19 Java/Android
mybatis-plus模糊查询指定字段
Apr 28 Java/Android
Spring Cloud OpenFeign模版化客户端
Jun 25 Java/Android
MyBatis在注解上使用动态SQL方式(@select使用if)
Jul 07 Java/Android
Android实现获取短信验证码并自动填充
May 21 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
PhpStorm 如何优雅的调试Hyperf的方法步骤
2019/11/24 PHP
Thinkphp 框架配置操作之配置加载与读取配置实例分析
2020/05/15 PHP
JS 树形递归实例代码
2010/05/18 Javascript
小试JQuery的AutoComplete插件
2011/05/04 Javascript
js实现按钮颜色渐变动画效果
2015/08/20 Javascript
javascript实现数组去重的多种方法
2016/03/14 Javascript
js中用cssText设置css样式的简单方法
2016/09/19 Javascript
JS实现多级菜单中当前菜单不随页面跳转样式而发生变化
2017/05/30 Javascript
jquery单击文字或图片内容放大并居中显示
2017/06/23 jQuery
React Native 自定义下拉刷新上拉加载的列表的示例
2018/03/01 Javascript
使用jquery DataTable和ajax向页面显示数据列表的方法
2018/08/09 jQuery
每周一练 之 数据结构与算法(Stack)
2019/04/16 Javascript
vue中的inject学习教程
2019/04/24 Javascript
JS实现的检验身份证格式并输出出生日期,年龄,性别,出生地示例
2019/05/17 Javascript
jqGrid表格底部汇总、合计行footerrow处理
2019/08/21 Javascript
vue 使用原生组件上传图片的实例
2020/09/08 Javascript
[06:07]DOTA2-DPC中国联赛3月5日Recap集锦
2021/03/11 DOTA
Python的Django框架使用入门指引
2015/04/15 Python
Python list操作用法总结
2015/11/10 Python
Python爬取十篇新闻统计TF-IDF
2018/01/03 Python
python实现用户答题功能
2018/01/17 Python
python基础教程项目五之虚拟茶话会
2018/04/02 Python
Python 中的range(),以及列表切片方法
2018/07/02 Python
python利用wx实现界面按钮和按钮监听和字体改变的方法
2019/07/17 Python
python连接、操作mongodb数据库的方法实例详解
2019/09/11 Python
python进行二次方程式计算的实例讲解
2020/12/06 Python
html5标记文字_动力节点Java学院整理
2017/07/11 HTML / CSS
乐高瑞士官方商店:LEGO CH
2020/08/16 全球购物
.net面试题
2016/09/17 面试题
西安启天科技有限公司网络工程师面试题笔试题
2016/06/12 面试题
2014年五四青年节活动策划书
2014/04/22 职场文书
小学毕业演讲稿
2014/04/25 职场文书
学习雷锋活动总结
2014/04/29 职场文书
幼儿园2014年度工作总结
2014/11/10 职场文书
2014年质检员工作总结
2014/11/18 职场文书
乌镇导游词
2015/02/02 职场文书