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 相关文章推荐
springboot如何初始化执行sql语句
Jun 22 Java/Android
springcloud之Feign超时问题的解决
Jun 24 Java/Android
Java中多线程下载图片并压缩能提高效率吗
Jul 01 Java/Android
Java org.w3c.dom.Document 类方法引用报错
Aug 07 Java/Android
springboot如何接收application/x-www-form-urlencoded类型的请求
Nov 02 Java/Android
Java 垃圾回收超详细讲解记忆集和卡表
Apr 08 Java/Android
零基础学java之循环语句的使用
Apr 10 Java/Android
Android Studio实现带三角函数对数运算功能的高级计算器
May 20 Java/Android
利用正则表达式匹配浮点型数据
May 30 Java/Android
tree shaking对打包体积优化及作用
Jul 07 Java/Android
app场景下uniapp的扫码记录
Jul 23 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中SESSION使用中的一点经验总结
2012/03/30 PHP
php操作(删除,提取,增加)zip文件方法详解
2015/03/12 PHP
详解js异步文件加载器
2016/01/24 PHP
laravel-admin select框默认选中的方法
2019/10/03 PHP
一款JavaScript压缩工具:X2JSCompactor
2007/06/13 Javascript
jQuery的链式调用浅析
2010/12/03 Javascript
单击按钮显示隐藏子菜单经典案例
2013/01/04 Javascript
Node.js和MongoDB实现简单日志分析系统
2015/04/25 Javascript
jQuery可见性过滤选择器用法示例
2016/09/09 Javascript
js数组与字符串常用方法总结
2017/01/13 Javascript
JS对象的深度克隆方法示例
2017/03/16 Javascript
JS简单判断字符在另一个字符串中出现次数的2种常用方法
2017/04/20 Javascript
微信小程序绑定手机号获取验证码功能
2019/10/22 Javascript
Element Alert警告的具体使用方法
2020/07/27 Javascript
js删除对象中的某一个字段的方法实现
2021/01/11 Javascript
[33:33]完美世界DOTA2联赛PWL S2 FTD.C vs SZ 第二场 11.27
2020/11/30 DOTA
python函数参数*args**kwargs用法实例
2013/12/04 Python
python 实现红包随机生成算法的简单实例
2017/01/04 Python
Python 多线程实例详解
2017/03/25 Python
python生成excel的实例代码
2017/11/08 Python
python with提前退出遇到的坑与解决方案
2018/01/05 Python
Python实现的直接插入排序算法示例
2018/04/29 Python
python函数的万能参数传参详解
2019/07/26 Python
Python 多线程,threading模块,创建子线程的两种方式示例
2019/09/29 Python
Python + selenium + crontab实现每日定时自动打卡功能
2020/03/31 Python
Django+RestFramework API接口及接口文档并返回json数据操作
2020/07/12 Python
canvas压缩图片以及卡片制作的方法示例
2018/12/04 HTML / CSS
微软香港官网及网上商店:Microsoft HK
2016/09/01 全球购物
后进生转化工作制度
2014/01/17 职场文书
冬季施工防火方案
2014/05/17 职场文书
计算机专业自荐信范文
2014/05/28 职场文书
行政专员岗位职责说明书
2014/09/01 职场文书
党的群众路线教育实践活动对照检查材料
2014/09/22 职场文书
英文版辞职信
2015/02/28 职场文书
教你用Python+selenium搭建自动化测试环境
2021/06/18 Python
浅谈Redis的keys命令到底有多慢
2021/10/05 Redis