大数据框架之Hadoop:HDFS(三)HDFS客户端操作(开发重点)

news2024/9/21 16:26:11

3.1 HDFS客户端环境准备

1.根据自己电脑的操作系统拷贝对应的编译后的hadoop jar包到非中文路径(例如:D:\javaEnv\hadoop-2.77),如下图所示。

image-20230202212658501

2.配置HADOOP_HOME环境变量,如下图所示。

image-20230202212934604

3.配置Path环境变量,如下图所示。

image-20230202212816698

4.创建一个Maven工程HdfsClientDemo

5.导入相应的依赖坐标+日志添加

<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.8.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-common</artifactId>
			<version>2.7.7</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-client</artifactId>
			<version>2.7.7</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-hdfs</artifactId>
			<version>2.7.7</version>
		</dependency>
		<dependency>
			<groupId>jdk.tools</groupId>
			<artifactId>jdk.tools</artifactId>
			<version>1.8</version>
			<scope>system</scope>
			<systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
		</dependency>
</dependencies>

注意:如果Eclipse/Idea打印不出日志,在控制台上只显示

1.log4j:WARN No appenders could be found for logger (org.apache.hadoop.util.Shell).  
2.log4j:WARN Please initialize the log4j system properly.  
3.log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

需要在项目的src/main/resources目录下,新建一个文件,命名为“log4j.properties”,在文件中填入

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

6.创建包名:com.atguigu.hdfs

7.创建HdfsClient类

public class HdfsClient{
    @Test
    public void testMkdirs() throws IOException, InterruptedException, URISyntaxException {

        // 1 获取文件系统
        Configuration configuration = new Configuration();
        // 配置在集群上运行
        // configuration.set("fs.defaultFS", "hdfs://hdp101:9000");
        // FileSystem fs = FileSystem.get(configuration);

        FileSystem fs = FileSystem.get(new URI("hdfs://hdp101:9000"), configuration, "root");

        // 2 创建目录
        fs.mkdirs(new Path("/1108/daxian/banzhang"));

        // 3 关闭资源
        fs.close();
    }
}

8.执行程序

运行时需要配置用户名称,如图3-7所示

客户端去操作HDFS时,是有一个用户身份的。默认情况下,HDFS客户端API会从JVM中获取一个参数来作为自己的用户身份:-DHADOOP_USER_NAME=root,root为用户名称。

3.2HDFS的API操作

3.2.1HDFS文件上传(测试参数优先级)

1.编写源代码

@Test
public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException {

    // 1 获取文件系统
    Configuration configuration = new Configuration();
    configuration.set("dfs.replication", "2");
    FileSystem fs = FileSystem.get(new URI("hdfs://hdp101:9000"), configuration, "root");

    // 2 上传文件
    fs.copyFromLocalFile(new Path("e:/banzhang.txt"), new Path("/banzhang.txt"));

    // 3 关闭资源
    fs.close();

    System.out.println("over");
}

2.将hdfs-site.xml拷贝到项目的根目录下

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>
	<property>
		<name>dfs.replication</name>
        <value>1</value>
	</property>
</configuration>

3.参数优先级

参数优先级排序:(1)客户端代码中设置的值 >(2)ClassPath下的用户自定义配置文件 >(3)然后是服务器的默认配置

3.2.2HDFS文件下载

@Test
public void testCopyToLocalFile() throws IOException, InterruptedException, URISyntaxException{

    // 1 获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hdp101:9000"), configuration, "root");

    // 2 执行下载操作
    // boolean delSrc 指是否将原文件删除
    // Path src 指要下载的文件路径
    // Path dst 指将文件下载到的路径
    // boolean useRawLocalFileSystem 是否开启文件校验
    fs.copyToLocalFile(false, new Path("/banzhang.txt"), new Path("e:/banhua.txt"), true);

    // 3 关闭资源
    fs.close();
}

3.2.3HDFS文件夹删除

@Test
public void testDelete() throws IOException, InterruptedException, URISyntaxException{

    // 1 获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hdp101:9000"), configuration, "root");

    // 2 执行删除
    fs.delete(new Path("/1108/"), true);

    // 3 关闭资源
    fs.close();
}

3.2.4 HDFS文件名更改

@Test
public void testRename() throws IOException, InterruptedException, URISyntaxException{

    // 1 获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hdp101:9000"), configuration, "root");

    // 2 修改文件名称
    fs.rename(new Path("/banzhang.txt"), new Path("/banhua.txt"));

    // 3 关闭资源
    fs.close();
}

3.2.5HDFS文件详情查看

@Test
public void testListFiles() throws IOException, InterruptedException, URISyntaxException{

    // 1获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hdp101:9000"), configuration, "root");

    // 2 获取文件详情
    RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);

    while(listFiles.hasNext()){
        LocatedFileStatus status = listFiles.next();
        // 输出详情
        // 文件名称
        System.out.println(status.getPath().getName());
        // 长度
        System.out.println(status.getLen());
        // 权限
        System.out.println(status.getPermission());
        // 分组
        System.out.println(status.getGroup());

        // 获取存储的块信息
        BlockLocation[] blockLocations = status.getBlockLocations();
        for (BlockLocation blockLocation : blockLocations) {
            // 获取块存储的主机节点
            String[] hosts = blockLocation.getHosts();
            for (String host : hosts) {
                System.out.println(host);
            }
        }

        System.out.println("-----------班长的分割线----------");
    }

    // 3 关闭资源
    fs.close();
}

3.2.6HDFS文件和文件夹判断

@Test
public void testListStatus() throws IOException, InterruptedException, URISyntaxException{

    // 1 获取文件配置信息
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hdp101:9000"), configuration, "root");

    // 2 判断是文件还是文件夹
    FileStatus[] listStatus = fs.listStatus(new Path("/"));

    for (FileStatus fileStatus : listStatus) {

        // 如果是文件
        if (fileStatus.isFile()) {
            System.out.println("f:"+fileStatus.getPath().getName());
        }else {
            System.out.println("d:"+fileStatus.getPath().getName());
        }
    }

    // 3 关闭资源
    fs.close();
}

3.3 HDFS的I/O流操作

上面我们学的API操作HDFS系统都是框架封装好的。那么如果我们想自己实现上述API的操作该怎么实现呢?

我们可以采用IO流的方式实现数据的上传和下载。

3.3.1HDFS文件上传

1.需求:把本地e盘上的banhua.txt文件上传到HDFS根目录

2.编写代码

@Test
public void putFileToHDFS() throws IOException, InterruptedException, URISyntaxException {

    // 1 获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hdp101:9000"), configuration, "root");

    // 2 创建输入流
    FileInputStream fis = new FileInputStream(new File("e:/banzhang.txt"));

    // 3 获取输出流
    FSDataOutputStream fos = fs.create(new Path("/banhua.txt"));

    // 4 流对拷
    IOUtils.copyBytes(fis, fos, configuration);

    // 5 关闭资源
    IOUtils.closeStream(fos);
    IOUtils.closeStream(fis);
    fs.close();
}

3.3.2HDFS文件下载

1.需求:从HDFS上下载banhua.txt文件到本地e盘上

2.编写代码

// 文件下载
@Test
public void getFileFromHDFS() throws IOException, InterruptedException, URISyntaxException{

    // 1 获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hdp101:9000"), configuration, "root");

    // 2 获取输入流
    FSDataInputStream fis = fs.open(new Path("/banhua.txt"));

    // 3 获取输出流
    FileOutputStream fos = new FileOutputStream(new File("e:/banhua.txt"));

    // 4 流的对拷
    IOUtils.copyBytes(fis, fos, configuration);

    // 5 关闭资源
    IOUtils.closeStream(fos);
    IOUtils.closeStream(fis);
    fs.close();
}

3.3.3定位文件读取

1.需求:分块读取HDFS上的大文件,比如根目录下的/hadoop-2.7.2.tar.gz

2.编写代码

(1)下载第一块

@Test
public void readFileSeek1() throws IOException, InterruptedException, URISyntaxException{

    // 1 获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hdp101:9000"), configuration, "root");

    // 2 获取输入流
    FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.7.tar.gz"));

    // 3 创建输出流
    FileOutputStream fos = new FileOutputStream(new File("e:/hadoop-2.7.7.tar.gz.part1"));

    // 4 流的拷贝
    byte[] buf = new byte[1024];

    for(int i =0 ; i < 1024 * 128; i++){
        fis.read(buf);
        fos.write(buf);
    }

    // 5关闭资源
    IOUtils.closeStream(fis);
    IOUtils.closeStream(fos);
    fs.close();
}

(2)下载第二块

@Test
public void readFileSeek2() throws IOException, InterruptedException, URISyntaxException{

    // 1 获取文件系统
    Configuration configuration = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hdp101:9000"), configuration, "root");

    // 2 打开输入流
    FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.7.tar.gz"));

    // 3 定位输入数据位置
    fis.seek(1024*1024*128);

    // 4 创建输出流
    FileOutputStream fos = new FileOutputStream(new File("e:/hadoop-2.7.7.tar.gz.part2"));

    // 5 流的对拷
    IOUtils.copyBytes(fis, fos, configuration);

    // 6 关闭资源
    IOUtils.closeStream(fis);
    IOUtils.closeStream(fos);
}

(3)合并文件

在Window命令窗口中进入到目录E:\,然后执行如下命令,对数据进行合并

type hadoop-2.7.2.tar.gz.part2 >> hadoop-2.7.2.tar.gz.part1

合并完成后,将hadoop-2.7.2.tar.gz.part1重新命名为hadoop-2.7.2.tar.gz。解压发现该tar包非常完整。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/343433.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

分布式项目-品牌管理(7)

【今日成果】&#xff1a; //啊哈哈哈 &#xff0c; 莫名其妙入选了。 【快速回顾】&#xff1a; &#xff08;1&#xff09;&#xff1a; 虽然提交表单的时候前端做了校验&#xff0c;但是通过PostMAN接口调试&#xff0c;我们发现不规范的数据还是会被存储到数据库中&am…

前端基础知识6

谈谈你对语义化标签的理解语义化标签就是具有语义的标签&#xff0c;它可以清晰地向我们展示它的作用和用途。 清晰的代码结构&#xff1a;在页面没有css的情况下&#xff0c;也能够呈现出清晰的代码内容 有利于SEO: 爬虫依赖标签来确定关键字的权重&#xff0c;因此可以和搜索…

Android 一体机研发之修改系统设置————声音

Android 一体机研发之修改系统设置————屏幕亮度 Android 一体机研发之修改系统设置————声音 Android 一体机研发之修改系统设置————自动锁屏 修改系统设置系列篇章马上开张了&#xff01; 本章将为大家细节讲解声音。 对于声音功能大家都不陌生&#xff0c;在多…

Java虚拟机(JVM)调优思路

title: Java虚拟机&#xff08;JVM&#xff09;调优思路 date: 2022-04-09 00:00:00 tags: JVM性能调优 categories:Java 调什么 内存方面 JVM需要的内存总大小各块内存分配&#xff0c;新生代、老年代、存活区选择合适的垃圾回收算法、控制GC停顿次数和时间解决内存泄露的问…

Appium移动自动化测试——app控件获取之uiautomatorviewer

下载手机YY http://yydl.duowan.com/mobile/yymobile_client-android/5.4.2/yymobile_client-5.4.2-881.apk 若链接失效&#xff0c;请自行百度 新建maven空白工程 前置条件&#xff1a;安装eclipse&#xff0c;及其maven插件&#xff0c;请自行百度 新建的工程如下&#xf…

Kylin查询下压的设置、Sparder查询引擎详细介绍、HDFS文件目录含义

目录1. 查询下压设置2. Sparder查询引擎详细介绍3. HDFS文件目录含义1. 查询下压设置 如果未开启查询下压&#xff0c;则查询有很多限制。这是因为只能查询cube中的数据&#xff0c;而不能通过spark sql查询Hive中的源数据 开启查询下压&#xff0c;优先从cube中查询数据&…

百度前端常考vue面试题(附答案)

怎么实现路由懒加载呢 这是一道应用题。当打包应用时&#xff0c;JavaScript 包会变得非常大&#xff0c;影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块&#xff0c;然后当路由被访问时才加载对应组件&#xff0c;这样就会更加高效 // 将 // import UserD…

因新硬件支持内核问题Ubuntu 22.04.2推迟发布

导读Ubuntu 22.04.2 LTS 原定于 2 月 9 日发布。但 Canonical 宣布该版本因各种问题不得不推迟两周&#xff0c;定于 2 月 23 日发布。 Ubuntu 22.04.2 LTS 原定于 2 月 9 日发布。但 Canonical 宣布该版本因各种问题不得不推迟两周&#xff0c;定于 2 月 23 日发布。 Canonica…

2023全网最火的接口自动化测试,一看就会

目录 接口自动化测试用例设计Excel接口测试用例访问MySQL接口测试用例访问PyTest测试框架接口自动化测试必备技能-HTTP协议request库实现接口请求 引言 与UI相比&#xff0c;接口一旦研发完成&#xff0c;通常变更或重构的频率和幅度相对较小。因此做接口自动化的性价比更高&…

AI是超越还是桎梏?从ChatGPT到5G+AI,我们在聊什么?

从家常里短聊到科技创新&#xff0c;从人文故事探讨到物理科学&#xff0c;诞生2个月用户即破亿的ChatGPT正成为火爆全球的AI应用工具&#xff0c;其强大的能力超乎人们想象。这款几乎博学多识的聊天机器人能运用AI系统进行简洁的交流&#xff0c;完成各种指令信息的表达。面对…

Prometheus 自动发现监控AWS EC2实例

本文章简述对接自动发现AWS云EC2实例 前提环境&#xff1a; PromethuesGrafanaAWS IAM权限 涉及参考文档&#xff1a; AWS EC2Grafana 通用监控模板 一、IAM 用户创建 1、创建Prometheus 策略 策略规则&#xff1a; {"Version": "2012-10-17",&quo…

【实际开发18】- 静态 3

目录 1. 调试与评估 2. 单元测试的管理 1. 单元测试的文档 3. 系统集成的模式与方法 1. 集成测试前的准备 2. 集成测试的模式 3. 大棒集成方法 ( Big-bang Integration) 4. 自顶向下和自底向上集成方法 1. 自顶向下法 ( Top-down Integration ) 2. 自底向上法 ( Bott…

linux如何查看编译器支持的C++版本(支持C++11、支持C++14、支持C++17、支持C++20)(编译时不指定g++版本,默认使用老版本编译)

文章目录C各个版本C11C14C17C20查看自己的编译器支持C哪个版本注意&#xff1a;编译时不指定g版本&#xff0c;默认使用老版本编译&#xff08;存疑&#xff09;C各个版本 C11 C11是一个重要的C标准版本&#xff0c;于2011年发布。C11带来了许多重要的改进&#xff0c;包括&a…

vue3封装数值动态递增组件

vue3封装数值动态递增组件前言源码举个例子&#xff1a;前言 1&#xff09;使用技术&#xff1a; vue3.2 Ts 2&#xff09;组件接收参数&#xff1a; 参数类型意义是否可选valuenumber数值大小必填durationnumber递增动画持续时间&#xff08;单位&#xff1a;s&#xff09;…

PyTorch学习笔记

PyTorch学习笔记&#xff08;一&#xff09;&#xff1a;PyTorch环境安装 往期学习资料推荐&#xff1a; 1.Pytorch实战笔记_GoAI的博客-CSDN博客 2.Pytorch入门教程_GoAI的博客-CSDN博客 安装参考&#xff1a; 1.视频教程&#xff1a;3分钟深度学习【环境搭建】CUDA Anacon…

javascript测试二

一、 选择题&#xff08;共10题&#xff0c;每题2分&#xff09;1、在JavaScript中&#xff0c;想要一次跳出方法的多层循环结构需要用&#xff08;C &#xff09; A) breakB) continueC) returnD) false2、 下列关于嵌套循环以下说法正确的一项是(A )。A) 每一种循环结构内部也…

Elipse报错:Failed to load the JNI shared library jvm.dll解决方法

情景 导入Elipse的项目中有jar包和64位版本的JDK不兼容。 于是我安装了32位版本的JDK。 配置好系统环境后&#xff0c;重启Eclipse却遇到了这个问题。 原因 搜索后了解到&#xff0c;是因为Eclipse版本与JDK版本不匹配。 我的Eclipse是64位的&#xff0c;但JDK配置是32位的…

科技云报道:2023年,可观测性迎来哪些新趋势?

科技云报道原创。 可观测性不是一个新鲜的名词&#xff0c;但是近年来随着云原生技术的发展&#xff0c;在带来效率、可用性提升的同时也增加了复杂度&#xff0c;而可观测性成为降低这种复杂度的唯一手段&#xff0c;因此被推到了前所未有的重要地位。 Gartner将应用可观测…

前端面试常考 | 浅拷贝与深拷贝

文章目录一. 前言1. 概述2. 数据类型3. 存储区别二. 深浅拷贝1.深浅拷贝的定义2. 基本数据类型的拷贝3. 引用类型的拷贝4. 实现 “浅” 拷贝1. Object.assign()2. slice()3. concat()方法4. es6展开运算符5. 实现 “深” 拷贝1. JSON.parse(JSON.stringify(obj))2. lodash3. 递…

ASEMI代理FGH60N60,安森美FGH60N60车规级IGBT

编辑-Z 安森美FGH60N60车规级IGBT参数&#xff1a; 型号&#xff1a;FGH60N60 集电极到发射极电压&#xff08;VCES&#xff09;&#xff1a;600V 栅极到发射极电压&#xff08;VGES&#xff09;&#xff1a;20V 收集器电流&#xff08;IC&#xff09;&#xff1a;120A 二…