2021-04-17

数据来源:拉钩教育大数据高薪开发训练营

Hadoop学习第六部分:hdfs的java客户端

1)客户端环境准备

1.将Hadoop-2.9.2安装包解压到非中文路径(例如:E:\hadoop-2.9.2)
在这里插入图片描述
2.配置HADOOP_HOME环境变量
在这里插入图片描述
3.配置Path环境变量。
在这里插入图片描述
4.创建一个Maven工程ClientDemo
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.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-client
-->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-hdfs --
>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>

为了便于控制程序运行打印的日志数量,需要在项目的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.lagou.hdfs
7.创建HdfsClient类

public class HdfsClient{
@Test
public void testMkdirs() throws IOException, InterruptedException,
URISyntaxException {
// 1 获取文件系统
Configuration configuration = new Configuration();
// 配置在集群上运行
// configuration.set("fs.defaultFS", "hdfs://linux121:9000");
// FileSystem fs = FileSystem.get(configuration);
FileSystem fs = FileSystem.get(new URI("hdfs://linux121:9000"),
configuration, "root");
// 2 创建目录
fs.mkdirs(new Path("/test"));
// 3 关闭资源
fs.close();
}
}

遇到问题:
如果不指定操作HDFS集群的用户信息,默认是获取当前操作系统的用户信息,出现权限被拒绝的问题,报错如下:

在这里插入图片描述

2)HDFS的API操作

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://linux121:9000"),
configuration, "root");
// 2 上传文件
fs.copyFromLocalFile(new Path("e:/lagou.txt"), new
Path("/lagou.txt"));
// 3 关闭资源
fs.close();
System.out.println("end");
}

将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>

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

2. 下载文件

@Test
public void testCopyToLocalFile() throws IOException, InterruptedException,
URISyntaxException{
// 1 获取文件系统
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://linux121:9000"),
configuration, "root");
// 2 执行下载操作
// boolean delSrc 指是否将原文件删除
// Path src 指要下载的文件路径
// Path dst 指将文件下载到的路径
// boolean useRawLocalFileSystem 是否开启文件校验
fs.copyToLocalFile(false, new Path("/lagou.txt"), new
Path("e:/lagou_copy.txt"), true);
// 3 关闭资源
fs.close();
}

3. 删除文件/文件夹

@Test
public void testDelete() throws IOException, InterruptedException,
URISyntaxException{
// 1 获取文件系统
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://linux121:9000"),
configuration, "root");
// 2 执行删除
fs.delete(new Path("/api_test/"), true);
// 3 关闭资源
fs.close();
}

4. 查看文件名称、权限、长度、块信息

@Test
public void testListFiles() throws IOException, InterruptedException,
URISyntaxException{
// 1获取文件系统
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://linux121: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();
}

5. 文件夹判断

@Test
public void testListStatus() throws IOException, InterruptedException,
URISyntaxException{
// 1 获取文件配置信息
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://linux121: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();
}

以上我们使用的API操作都是HDFS系统框架封装好的。我们自己也可以采用IO流的方式实现文件的上传和下载。

3) I/O流操作HDFS

1. 文件上传

1.需求:把本地e盘上的lagou.txt文件上传到HDFS根目录
2.编写代码

@Test
public void putFileToHDFS() throws IOException, InterruptedException,
URISyntaxException {
// 1 获取文件系统
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://linux121:9000"),
configuration, "root");
// 2 创建输入流
FileInputStream fis = new FileInputStream(new File("e:/lagou.txt"));
// 3 获取输出流
FSDataOutputStream fos = fs.create(new Path("/lagou_io.txt"));
// 4 流对拷
IOUtils.copyBytes(fis, fos, configuration);
// 5 关闭资源
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
fs.close();
}

2. 文件下载

1.需求:从HDFS上下载lagou.txt文件到本地e盘上
2.编写代码
// 文件下载

@Test
public void getFileFromHDFS() throws IOException, InterruptedException,
URISyntaxException{
// 1 获取文件系统
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://linux121:9000"),
configuration, "root");
// 2 获取输入流
FSDataInputStream fis = fs.open(new Path("/lagou_io.txt"));
// 3 获取输出流
FileOutputStream fos = new FileOutputStream(new
File("e:/lagou_io_copy.txt"));
// 4 流的对拷
IOUtils.copyBytes(fis, fos, configuration);
// 5 关闭资源
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
fs.close();
}

3. seek 定位读取

1.需求:将HDFS上的lagou.txt的内容在控制台输出两次
2.编写代码

@Test
public void readFileSeek2() throws IOException, InterruptedException,
URISyntaxException{
// 1 获取文件系统
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://linux121:9000"),
configuration, "root");
// 2 打开输入流,读取数据输出到控制台
FSDataInputStream in = null;
try{
in= fs.open(new Path("/lagou.txt"));
IOUtils.copyBytes(in, System.out, 4096, false);
in.seek(0); //从头再次读取
IOUtils.copyBytes(in, System.out, 4096, false);
}finally {
IOUtils.closeStream(in);
}
}

注意
windows解压安装Hadoop后,在调用相关API操作HDFS集群时可能会报错,这是由于Hadoop安装缺少windows操作系统相关文件所致,如下图:
在这里插入图片描述
解决方案:
从资料文件夹中找到winutils.exe拷贝放到windows系统Hadoop安装目录的bin目录下即可!!
HDFS文件系统权限问题
hdfs的文件权限机制与linux系统的文件权限机制类似!!
r:read w:write x:execute 权限x对于文件表示忽略,对于文件夹表示是否有权限访问其内容,如果linux系统用户zhangsan使用hadoop命令创建一个文件,那么这个文件在HDFS当中的owner就是zhangsan;HDFS文件权限的目的,防止好人做错事,而不是阻止坏人做坏事。HDFS相信你告诉我你是谁,你就是谁!!
解决方案
指定用户信息获取FileSystem对象
关闭HDFS集群权限校验

vim hdfs-site.xml
#添加如下属性
<property>
<name>dfs.permissions</name>
<value>true</value>
</property>

修改完成之后要分发到其它节点,同时要重启HDFS集群
基于HDFS权限本身比较鸡肋的特点,我们可以彻底放弃HDFS的权限校验,如果生产环境中,我们可以考虑借助kerberos以及sentry等安全框架来管理大数据集群安全。所以我们直接修改HDFS的根目录权限为777

hadoop fs -chmod -R 777 /

4)参考代码

package com.lagou.hdfs;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
public class HdfsClientDemo {
FileSystem fs = null;
Configuration configuration = null;
@Before
public void init() throws URISyntaxException, IOException,
InterruptedException {
//1 获取Hadoop 集群的configuration对象
configuration = new Configuration();
// configuration.set("fs.defaultFS", "hdfs://linux121:9000");
// configuration.set("dfs.replication", "2");
//2 根据configuration获取Filesystem对象
fs = FileSystem.get(new URI("hdfs://linux121:9000"), configuration,
"root");
}
@After
public void destory() throws IOException {
//4 释放FileSystem对象(类似数据库连接)
fs.close();
}
@Test
public void testMkdirs() throws URISyntaxException, IOException,
InterruptedException {
// FileSystem fs = FileSystem.get(configuration);
//3 使用FileSystem对象创建一个测试目录
fs.mkdirs(new Path("/api_test2"));
}
//上传文件
@Test
public void copyFromLocalToHdfs() throws URISyntaxException, IOException,
InterruptedException {
//上传文件
//src:源文件目录:本地路径
//dst:目标文件目录,hdfs路径
fs.copyFromLocalFile(new Path("e:/lagou.txt"), new Path("/lagou.txt"));
//上传文件到hdfs默认是3个副本,
//如何改变上传文件的副本数量?
//1 configuration对象中指定新的副本数量
}
//下载文件
@Test
public void copyFromHdfsToLocal() throws URISyntaxException, IOException,
InterruptedException {
final FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
for (FileStatus fileStatus : fileStatuses) {
final boolean flag = fileStatus.isFile();
if (flag) {
System.out.println("文件:" + fileStatus.getPath().getName());
} else {
System.out.println("文件夹:" + fileStatus.getPath().getName());
}
}
}
//使用IO流操作HDFS
//上传文件:准备输入流读取本地文件,使用hdfs的输出流写数据到hdfs
@Test
public void uploadFileIO() throws IOException {
//1. 读取本地文件的输入流
final FileInputStream inputStream = new FileInputStream(new
File("e:/lagou.txt"));
//2. 准备写数据到hdfs的输出流
final FSDataOutputStream outputStream = fs.create(new
Path("/lagou.txt"));
// 3.输入流数据拷贝到输出流 :数组的大小,以及是否关闭流底层有默认值
IOUtils.copyBytes(inputStream, outputStream, configuration);
//4.可以再次关闭流
IOUtils.closeStream(outputStream);
IOUtils.closeStream(inputStream);
}
//下载文件
@Test
public void downLoadFileIO() throws IOException {
//1. 读取hdfs文件的输入流
final FSDataInputStream in = fs.open(new Path("/lagou.txt"));
//2. 本地文件的输出流
final FileOutputStream out = new FileOutputStream(new
File("e:/lagou_io_copy.txt"));
//3. 流的拷贝
IOUtils.copyBytes(in, out, configuration);
//4.可以再次关闭流
IOUtils.closeStream(out);
IOUtils.closeStream(in);
}
//seek定位读取hdfs指定文件 :使用io流读取/lagou.txt文件并把内容输出两次,本质就是读取文
件内容两次并输出
@Test
public void seekReadFile() throws IOException {
//1 创建一个读取hdfs文件的输入流
final FSDataInputStream in = fs.open(new Path("/lagou.txt"));
//2.控制台数据:System.out
//3 实现流拷贝,输入流--》控制台输出
// IOUtils.copyBytes(in, System.out, configuration);
IOUtils.copyBytes(in, System.out, 4096, false);
//4. 再次读取文件
in.seek(0); //定位从0偏移量(文件头部)再次读取
IOUtils.copyBytes(in, System.out, 4096, false);
//5.关闭输入流
IOUtils.closeStream(in);
}
}

学习产出:

提示:这里统计学习计划的总量
例如:
1、 技术笔记 2 遍
2、优快云 技术博客 3 篇
3、 学习的 vlog 视频 1 个

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值