HDFS的API操作


创建maven工程并导入jar包

  <repositories>
<repository>
<id>cloudera</id>
<url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
</repository>
</repositories>

  再从这里找需要的jar包:https://www.cloudera.com/documentation/enterprise/release-notes/topics/cdh_vd_cdh5_maven_repo_514x.html

<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.6.0-mr1-cdh5.14.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.6.0-cdh5.14.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>2.6.0-cdh5.14.0</version>
</dependency> <dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-core</artifactId>
<version>2.6.0-cdh5.14.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<!-- <verbal>true</verbal>-->
</configuration>
</plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<minimizeJar>true</minimizeJar>
</configuration>
</execution>
</executions>
</plugin>
<!-- <plugin>
<artifactId>maven-assembly-plugin </artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>cn.itcast.hadoop.db.DBToHdfs2</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>-->
</plugins>
</build>

使用URL的方式访问数据(重在了解)

import org.apache.commons.io.IOUtils;
import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;
import org.junit.Test; import java.io.*;
import java.net.MalformedURLException;
import java.net.URL; public class demo {
@Test
public void demo1() throws IOException {
//第一步:注册HDFS的URL,让java代码能够识别HDFS的URL形式
URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory()); InputStream inputStream = null;
FileOutputStream outputStream =null; //URL地址可以在hadoop配置文件core-site.xml中查看
String url = "hdfs://192.168.0.10:8020/test/yum.log"; //打开文件输入流
try {
inputStream =new URL(url).openStream();
outputStream = new FileOutputStream(new File("/Users/zhaozhuang/Downloads/hello.txt"));
IOUtils.copy(inputStream,outputStream);
}catch (IOException e){
e.printStackTrace();
}finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
}
}

上述代码中String url的出处


获取FileSystem的几种方式

  • 第一种方式获取FileSystem
	@Test
public void getFileSystem1() throws IOException {
/*
FileSystem是一个抽象类,获取抽象类的实例有两种方式
第一种,看看这个抽象类有没有提供什么方法,返回它本身
第二种,找子类
*/
Configuration configuration = new Configuration();
//如果这里不加任何配置,这里获取到的就是本地文件系统
configuration.set("fs.defaultFS","hdfs://node01:8020");
FileSystem fileSystem = FileSystem.get(configuration); System.out.println(fileSystem.toString());
fileSystem.close();
}
  • 第二种方式获取FileSystem
	@Test
public void getFileSystem2() throws URISyntaxException, IOException {
Configuration configuration = new Configuration();
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"), configuration); System.out.println(fileSystem.toString());
fileSystem.close();
}
  • 第三种方式获取FileSystem
	@Test
public void getFileSystem3() throws IOException {
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS","hdfs://node01:8020"); FileSystem fileSystem = FileSystem.newInstance(configuration); System.out.println(fileSystem.toString());
fileSystem.close();
}
  • 第四种方式获取FileSystem
	@Test
public void getFileSystem4() throws URISyntaxException, IOException {
Configuration configuration = new Configuration();
FileSystem fileSystem = FileSystem.newInstance(new URI("hdfs://node01:8020"), configuration); System.out.println(fileSystem.toString());
fileSystem.close();
}

递归遍历HDFS的所有文件

  • 通过递归遍历hdfs文件系统
	@Test
public void getAllFiles() throws URISyntaxException, IOException {
//获取HDFS
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"), new Configuration());
//获取文件的状态,可以通过fileStatuses来判断究竟是文件夹还是文件
FileStatus[] fileStatuses = fileSystem.listStatus(new Path("hdfs://node01:8020/"));
/**
循环遍历FileStatus,判断文件究竟是文件夹还是文件
如果是文件,直接输出路径
如果是文件夹,继续遍历
*/
for (FileStatus fileStatus : fileStatuses) {
if (fileStatus.isDirectory()){
//如果是文件夹,继续遍历(需要再写一个方法来获取文件夹中的文件)
getDirFiles(fileStatus.getPath(),fileSystem);
} else {
Path path = fileStatus.getPath();
System.out.println(path.toString());
}
}
} public void getDirFiles(Path path,FileSystem fileSystem) throws IOException {
//还是先获取文件的状态
FileStatus[] fileStatuses = fileSystem.listStatus(path);
//循环遍历fileStatus
for (FileStatus fileStatus : fileStatuses) {
if (fileStatus.isDirectory()){
getDirFiles(fileStatus.getPath(),fileSystem);
} else {
System.out.println(fileStatus.getPath().toString());
}
}
}
  • 官方提供的API直接遍历
	/**
* 通过hdfs直接提供的API进行遍历
*/
@Test
public void getAllFiles2() throws URISyntaxException, IOException {
//获取HDFS
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"), new Configuration());
//获取RemoteIterator 得到所有的文件或者文件夹,第一个参数指定遍历的路径,第二个参数表示是否要递归遍历
RemoteIterator<LocatedFileStatus> locatedFileStatusRemoteIterator = fileSystem.listFiles(new Path("hdfs://node01:8020/"), true);
//while循环遍历
while (locatedFileStatusRemoteIterator.hasNext()){
LocatedFileStatus next = locatedFileStatusRemoteIterator.next();
System.out.println(next.getPath().toString());
}
fileSystem.close();
}

下载文件到本地

	@Test
public void downloadFileToLocal() throws URISyntaxException, IOException {
//获取HDfS
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"), new Configuration());
//打开输入流,读取HDfS上的文件
FSDataInputStream inputStream = fileSystem.open(new Path("hdfs://node01:8020/test/yum.log"));
//用输出流,确定下载到本地的路径
FileOutputStream outputStream = new FileOutputStream(new File("/Users/zhaozhuang/Downloads/hello2.txt"));
//用IOUtils把文件下载下来
IOUtils.copy(inputStream,outputStream);
//关闭输入流和输出流
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
fileSystem.close();
}

在HDFS上创建文件夹

	@Test
public void mkdirs() throws URISyntaxException, IOException {
//获取HDFS
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"), new Configuration());
//创建文件夹
boolean mkdirs = fileSystem.mkdirs(new Path("/hello/mydir/test"));
//关闭系统
fileSystem.close();
}

HDFS文件上传

	@Test
public void uploadFileFromLocal() throws URISyntaxException, IOException {
//获取HDfS
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"), new Configuration());
//上传文件
fileSystem.copyFromLocalFile(new Path("/Users/zhaozhuang/Downloads/hello2.txt"),new Path("/"));
//关闭系统
fileSystem.close();
}

HDFS权限问题以及伪造用户

  • 首先停止hdfs集群,在node01机器上执行以下命令
cd /export/servers/hadoop-2.6.0-cdh5.14.0

stop-dfs.sh
  • 修改node01机器上的hdfs-site.xml当中的配置文件
<property>
<name>dfs.permissions</name>
<value>true</value>
</property>
  • 修改完成之后配置文件发送到其他机器上面去
scp hdfs-site.xml node02:$PWD
scp hdfs-site.xml node03:$PWD
  • 重启hdfs集群
start-dfs.sh
  • 随意上传一些文件到我们hadoop集群当中准备测试使用
cd /export/servers/hadoop-2.6.0-cdh5.14.0/etc/hadoop
hdfs dfs -mkdir /config
hdfs dfs -put *.xml /config
hdfs dfs -chmod 600 /config/core-site.xml
  • Java伪造root用户下载
	@Test
public void getConfig() throws URISyntaxException, IOException, InterruptedException {
//获取HDFS(第三个参数为伪造的用户)
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"), new Configuration(),"root");
//下载文件
fileSystem.copyToLocalFile(new Path("/config/core-site.xml"),new Path("/Users/ZhaoZhuang/Downloads/hello3.txt"));
//关闭系统
fileSystem.close();
}

HDFS的小文件合并

  • 在linux进行小文件合并
cd /export/servers

hdfs dfs -getmerge /config/*.xml ./hello.xml
  • 在java进行小文件合并
	@Test
public void mergeFiles() throws URISyntaxException, IOException, InterruptedException {
//获取HDFS
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"), new Configuration(), "root");
//创建输出流,在HDFS端创建一个合并文件
FSDataOutputStream outputStream = fileSystem.create(new Path("/bigFile.xml"));
//获取本地文件系统
LocalFileSystem local = FileSystem.getLocal(new Configuration());
//通过本地文件系统获取文件列表,为一个集合
FileStatus[] fileStatuses = local.listStatus(new Path("/Volumes/赵壮备份/大数据离线课程资料/3.大数据离线第三天/上传小文件合并"));
//遍历FileStatus
for (FileStatus fileStatus : fileStatuses) {
FSDataInputStream inputStream = local.open(fileStatus.getPath());
IOUtils.copy(inputStream,outputStream);
IOUtils.closeQuietly(inputStream);
}
IOUtils.closeQuietly(outputStream);
local.close();
fileSystem.close();
}

【Hadoop离线基础总结】HDFS的API操作的更多相关文章

  1. 【Hadoop离线基础总结】oozie的安装部署与使用

    目录 简单介绍 概述 架构 安装部署 1.修改core-site.xml 2.上传oozie的安装包并解压 3.解压hadooplibs到与oozie平行的目录 4.创建libext目录,并拷贝依赖包 ...

  2. 【Hadoop离线基础总结】impala简单介绍及安装部署

    目录 impala的简单介绍 概述 优点 缺点 impala和Hive的关系 impala如何和CDH一起工作 impala的架构及查询计划 impala/hive/spark 对比 impala的安 ...

  3. 【Hadoop离线基础总结】Hive调优手段

    Hive调优手段 最常用的调优手段 Fetch抓取 MapJoin 分区裁剪 列裁剪 控制map个数以及reduce个数 JVM重用 数据压缩 Fetch的抓取 出现原因 Hive中对某些情况的查询不 ...

  4. 【Hadoop离线基础总结】Hue的简单介绍和安装部署

    目录 Hue的简单介绍 概述 核心功能 安装部署 下载Hue的压缩包并上传到linux解压 编译安装启动 启动Hue进程 hue与其他框架的集成 Hue与Hadoop集成 Hue与Hive集成 Hue ...

  5. 【Hadoop离线基础总结】流量日志分析网站整体架构模块开发

    目录 数据仓库设计 维度建模概述 维度建模的三种模式 本项目中数据仓库的设计 ETL开发 创建ODS层数据表 导入ODS层数据 生成ODS层明细宽表 统计分析开发 流量分析 受访分析 访客visit分 ...

  6. 客户端操作 2 HDFS的API操作 3 HDFS的I/O流操作

    2 HDFS的API操作 2.1 HDFS文件上传(测试参数优先级) 1.编写源代码 // 文件上传 @Test public void testPut() throws Exception { Co ...

  7. HDFS03 HDFS的API操作

    HDFS的API操作 目录 HDFS的API操作 客户端环境准备 1.下载windows支持的hadoop 2.配置环境变量 3 在IDEA中创建一个Maven工程 HDFS的API实例 用客户端远程 ...

  8. 【Hadoop离线基础总结】Sqoop常用命令及参数

    目录 常用命令 常用公用参数 公用参数:数据库连接 公用参数:import 公用参数:export 公用参数:hive 常用命令&参数 从关系表导入--import 导出到关系表--expor ...

  9. hadoop hdfs java api操作

    package com.duking.util; import java.io.IOException; import java.util.Date; import org.apache.hadoop ...

随机推荐

  1. 5个有趣的Python小知识,结果令人意外

    1 字符串驻留 如果上面例子返回True,但是下面例子为什么是False: 这与Cpython 编译优化相关,行为称为字符串驻留,但驻留的字符串中只包含字母,数字或下划线. 2 相同值的不可变对象 这 ...

  2. 教你如何安装和使用Python pip

    前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:Starshot PS:如有需要Python学习资料的小伙伴可以加点击 ...

  3. Cobalt Strike系列教程第七章:提权与横向移动

    Cobalt Strike系列教程分享如约而至,新关注的小伙伴可以先回顾一下前面的内容: Cobalt Strike系列教程第一章:简介与安装 Cobalt Strike系列教程第二章:Beacon详 ...

  4. Win32 Disk Imager刻录过的U盘恢复容量的方法

    近日遇到一个问题,使用Win32 Disk Imager刻录过的U盘,想恢复使用,但无法正常使用. 按WIN+R键调出Win10运行框,输入diskmgmt.msc,打开磁盘管理工具. 看到U盘的状况 ...

  5. F. 蚂蚁装修

    单点时限: 2.0 sec 内存限制: 512 MB 还有一个月就开学了,爱学习的小蚂蚁想庆祝一下!于是它要把它的“家”装修一下.首先要做的就是贴地板.小蚂蚁“家”的地面可以看成一个2∗N 的方格 , ...

  6. echarts使用笔记

    1.解决列文字隔开问题,及文字太长问题解决. yAxis: [ { type : 'category', data : message.data[0].dataone, axisLabel: { in ...

  7. SpringMVC转发及重定向

    基础环境搭建请参考SringMVC入门程序 1:springmvc-servlet.xml <?xml version="1.0" encoding="UTF-8& ...

  8. for嵌套setTimeout的心得

    export default { data() { return { dialogList: [] } }, created() { this.setList() }, methods: { setL ...

  9. HTML之前端组成、标签

    详情见:https://www.cnblogs.com/liwenzhou/p/7988087.html https://www.cnblogs.com/zhangguosheng1121/p/109 ...

  10. 关于go的init函数

    亲测,如果加载一个包,如果一个包里的每个文件,均含有init函数,那么均会执行. 目前来看,init的执行顺序,是文件名称的自然排序进行执行的. 并且只是所加载包里的go文件的init函数执行,对于包 ...