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 11 Java/Android
解决tk mapper 通用mapper的bug问题
Jun 16 Java/Android
详解Java实现数据结构之并查集
Jun 23 Java/Android
IDEA使用SpringAssistant插件创建SpringCloud项目
Jun 23 Java/Android
Java移除无效括号的方法实现
Aug 07 Java/Android
idea以任意顺序debug多线程程序的具体用法
Aug 30 Java/Android
logback如何自定义日志存储
Aug 30 Java/Android
java多态注意项小结
Oct 16 Java/Android
Java字符缓冲流BufferedWriter
Apr 09 Java/Android
Android中的Launch Mode详情
Jun 05 Java/Android
AndroidStudio图片压缩工具ImgCompressPlugin使用实例
Aug 05 Java/Android
SpringBoot Http远程调用的方法
Aug 14 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正则表达式验证(邮件地址、Url地址、电话号码、邮政编码)
2016/03/14 PHP
Yii框架where查询用法实例分析
2019/10/22 PHP
js判断背景图片是否加载成功使用img的width实现
2013/05/29 Javascript
jquery如何把数组变为字符串传到服务端并处理
2014/04/30 Javascript
jQuery Timelinr实现垂直水平时间轴插件(附源码下载)
2016/02/16 Javascript
超链接怎么正确调用javascript函数
2016/05/23 Javascript
Node.js的Koa框架上手及MySQL操作指南
2016/06/13 Javascript
jQuery实现的简单排序功能示例【冒泡排序】
2017/01/13 Javascript
bootstrap响应式表格实例详解
2017/05/15 Javascript
AngularJS实现动态添加Option的方法
2017/05/17 Javascript
vue 录制视频并压缩视频文件的方法
2018/07/27 Javascript
工作中常用到的ES6语法
2018/09/04 Javascript
vue集成chart.js的实现方法
2019/08/20 Javascript
javascript 原型与原型链的理解及实例分析
2019/11/23 Javascript
复制粘贴功能的Python程序
2008/04/04 Python
Python升级提示Tkinter模块找不到的解决方法
2014/08/22 Python
用Python计算三角函数之atan()方法的使用
2015/05/15 Python
python二分查找算法的递归实现方法
2016/05/12 Python
python 批量修改/替换数据的实例
2018/07/25 Python
关于tensorflow softmax函数用法解析
2020/06/30 Python
什么是Python包的循环导入
2020/09/08 Python
CSS3美化表单控件全集
2016/06/29 HTML / CSS
HTML5的自定义属性data-*详细介绍和JS操作实例
2014/04/10 HTML / CSS
好的自荐信包括什么内容
2013/11/07 职场文书
旅游市场营销方案
2014/03/09 职场文书
大学生迟到检讨书500字
2014/10/17 职场文书
2014年人事科工作总结
2014/11/19 职场文书
2014年英语工作总结
2014/12/20 职场文书
2015年领导干部廉洁自律工作总结
2015/05/26 职场文书
学生会任命书范本
2015/09/21 职场文书
考教师资格证不要错过的4个最佳时机
2019/07/17 职场文书
开学季:喜迎新生,迎新标语少不了
2019/11/07 职场文书
教你解决往mysql数据库中存入汉字报错的方法
2021/05/06 MySQL
JavaWeb Servlet实现网页登录功能
2021/07/04 Java/Android
Html5同时支持多端sdk的小技巧
2021/11/17 HTML / CSS
Python可视化神器pyecharts绘制地理图表
2022/07/07 Python