bin/hadoop fs 具体命令 OR bin/hdfs dfs 具体命令
[root@linux121 hadoop-2.9.2]# bin/hdfs dfs
Usage: hadoop fs [generic options]
[-appendToFile ... ]
[-cat [-ignoreCrc] ...]
[-checksum ...]
[-chgrp [-R] GROUP PATH...]
[-chmod [-R] PATH...]
[-chown [-R] [OWNER][:[GROUP]] PATH...]
[-copyFromLocal [-f] [-p] [-l] [-d] ... ]
[-copyToLocal [-f] [-p] [-ignoreCrc] [-crc] ... ] [-count [-q] [-h] [-v] [-t []] [-u] [-x] ...] [-cp [-f] [-p | -p[topax]] [-d] ... ]
[-createSnapshot []]
[-deleteSnapshot ]
[-df [-h] [ ...]]
[-du [-s] [-h] [-x] ...]
[-expunge]
[-find ... ...]
[-get [-f] [-p] [-ignoreCrc] [-crc] ... ]
[-getfacl [-R] ]
[-getfattr [-R] {-n name | -d} [-e en] ]
[-getmerge [-nl] [-skip-empty-file] ]
[-help [cmd ...]]
[-ls [-C] [-d] [-h] [-q] [-R] [-t] [-S] [-r] [-u] [ ...]]
[-mkdir [-p] ...]
[-moveFromLocal ... ]
[-moveToLocal ]
[-mv ... ]
[-put [-f] [-p] [-l] [-d] ... ]
[-renameSnapshot ]
[-rm [-f] [-r|-R] [-skipTrash] [-safely] ...]
[-rmdir [--ignore-fail-on-non-empty] ...]
[-setfacl [-R] [{-b|-k} {-m|-x } ]|[--set
]]
[-setfattr {-n name [-v value] | -x name} ]
[-setrep [-R] [-w] ...]
[-stat [format] ...]
[-tail [-f] ]
[-test -[defsz] ]
[-text [-ignoreCrc] ...]
[-touchz ...]
[-truncate [-w] ...]
[-usage [cmd ...]]
Generic options supported are:
-conf specify an application configuration file
-D define a value for a given property
-fs specify default filesystem URL to use, overrides 'fs.defaultFS' property from configurations.
-jt specify a ResourceManager
-files specify a comma-separated list of files to be copied to the map reduce cluster
-libjars specify a comma-separated list of jar files to be included in the classpath
-archives specify a comma-separated list of archives to be unarchived on the compute machines
HDFS命令演示
启动Hadoop集群(方便后续的测试)
[root@linux121 hadoop-2.9.2]$ sbin/start-dfs.sh
[root@linux122 hadoop-2.9.2]$ sbin/start-yarn.sh
-help:输出这个命令参数
[root@linux121 hadoop-2.9.2]$ hadoop fs -help rm
-ls: 显示目录信息
[root@linux121 hadoop-2.9.2]$ hadoop fs -ls /
-mkdir:在HDFS上创建目录
[root@linux121 hadoop-2.9.2]$ hadoop fs -mkdir -p /lagou/bigdata
-moveFromLocal:从本地剪切粘贴到HDFS
[root@linux121 hadoop-2.9.2]$ touch hadoop.txt[root@linux121 hadoop-2.9.2]$ hadoop fs -moveFromLocal ./hadoop.txt /lagou/bigdata
-appendToFile:追加一个文件到已经存在的文件末尾
[root@linux121 hadoop-2.9.2]$ touch hdfs.txt
[root@linux121 hadoop-2.9.2]$ vi hdfs.txt
输入
namenode datanode block replication[root@linux121 hadoop-2.9.2]$ hadoop fs -appendToFile ./hdfs.txt /lagou/bigdata/hadoop.txt
-cat:显示文件内容
[root@linux121 hadoop-2.9.2]$ hadoop fs -cat /lagou/bigdata/hadoop.txt
-chgrp 、-chmod、-chown:Linux文件系统中的用法一样,修改文件所属权限
[root@linux121 hadoop-2.9.2]$ hadoop fs -chmod 666 /lagou/bigdata/hadoop.txt
[root@linux121 hadoop-2.9.2]$ hadoop fs -chown root:root /lagou/bigdata/hadoop.txt
-copyFromLocal:从本地文件系统中拷贝文件到HDFS路径去
[root@linux121 hadoop-2.9.2]$ hadoop fs -copyFromLocal README.txt /
-copyToLocal:从HDFS拷贝到本地
[root@linux121 hadoop-2.9.2]$ hadoop fs -copyToLocal /lagou/bigdata/hadoop.txt ./
-cp :从HDFS的一个路径拷贝到HDFS的另一个路径
[root@linux121 hadoop-2.9.2]$ hadoop fs -cp /lagou/bigdata/hadoop.txt /hdfs.txt
-mv:在HDFS目录中移动文件
[root@linux121 hadoop-2.9.2]$ hadoop fs -mv /hdfs.txt /lagou/bigdata/
-get:等同于copyToLocal,就是从HDFS下载文件到本地
[root@linux121 hadoop-2.9.2]$ hadoop fs -get /lagou/bigdata/hadoop.txt ./
-put:等同于copyFromLocal
[root@linux121 hadoop-2.9.2]$ hadoop fs -mkdir -p /user/root/test/
#本地文件系统创建yarn.txt
[root@linux121 hadoop-2.9.2]$ vim yarn.txt
resourcemanager nodemanager [root@linux121 hadoop-2.9.2]$ hadoop fs -put ./yarn.txt /user/root/test/
-tail:显示一个文件的末尾
[root@linux121 hadoop-2.9.2]$ hadoop fs -tail /user/root/test/yarn.txt
-rm:删除文件或文件夹
[root@linux121 hadoop-2.9.2]$ hadoop fs -rm /user/root/test/yarn.txt
-rmdir:删除空目录
[root@linux121 hadoop-2.9.2]$ hadoop fs -mkdir /test
[root@linux121 hadoop-2.9.2]$ hadoop fs -rmdir /test
-du统计文件夹的大小信息
[root@linux121 hadoop-2.9.2]$ hadoop fs -du -s -h /user/root/test[root@linux121 hadoop-2.9.2]$ hadoop fs -du -h /user/root/test
-setrep:设置HDFS中文件的副本数量
[root@linux121 hadoop-2.9.2]$ hadoop fs -setrep 10 /lagou/bigdata/hadoop.txt
图3-3 HDFS副本数量
这里设置的副本数只是记录在NameNode的元数据中,是否真的会有这么多副本,还得看DataNode的数量。因为目前只有3台设备,最多也就3个副本,只有节点数的增加到10台时,副本数才能达到10。




创建一个Maven工程ClientDemo
导入相应的依赖坐标+日志配置文件
junit
junit
RELEASE
org.apache.logging.log4j
log4j-core
2.8.2
org.apache.hadoop
hadoop-common
2.9.2
org.apache.hadoop
hadoop-client
2.9.2
org.apache.hadoop
hadoop-hdfs
2.9.2
为了便于控制程序运行打印的日志数量,需要在项目的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
创建包名:com.lagou.hdfs
创建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集群的用户信息,默认是获取当前操作系统的用户信息,出现权限被拒绝的问 题,报错如下:

编写源代码
@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拷贝到项目的根目录下
dfs.replication
1
参数优先级
参数优先级排序:(1)代码中设置的值 >(2)用户自定义配置文件 >(3)服务器的默认配置
@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();
}
@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();
}
@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 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();
}
@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流的方式实现文件的上传 和下载。
文件上传
需求:把本地e盘上的lagou.txt文件上传到HDFS根目录
编写代码
@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();
}
文件下载
需求:从HDFS上下载lagou.txt文件到本地e盘上
编写代码
// 文件下载
@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();
}
seek 定位读取
需求:将HDFS上的lagou.txt的内容在控制台输出两次
编写代码
@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);
}
}
注意

解决方案:
从资料文件夹中找到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集群权限校验```propertiesvim hdfs-site.xml#添加如下属性 dfs.permissions true ```修改完成之后要分发到其它节点,同时要重启HDFS集群- 基于HDFS权限本身比较鸡肋的特点,我们可以彻底放弃HDFS的权限校验,如果生产环境中我们可以考虑借助kerberos以及sentry等安全框架来管理大数据集群安全。所以我们直接修改HDFS的根目录权限为777```shellhadoop fs -chmod -R 777 /```参考代码```javapackage 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;@Beforepublic 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");}@Afterpublic void destory() throws IOException {//4 释放FileSystem对象(类似数据库连接) fs.close();}@Testpublic void testMkdirs() throws URISyntaxException, IOException, InterruptedException {//FileSystem fs = FileSystem.get(configuration); //3 使用FileSystem对象创建一个测试目录 fs.mkdirs(new Path("/api_test2"));}// 上传文件@Testpublic void copyFromLocalToHdfs() throws URISyntaxException, IOException, InterruptedException {//上传文件 //src:源文件目录:本地路径 //dst:目标文件目录,hdfs路径 fs.copyFromLocalFile(new Path("e:/lagou.txt"), new Path("/lagou.txt")); // 上传文件到hdfs默认是3个副本,//如何改变上传文件的副本数量? //1 configuration对象中指定新的副本数量 }// 下载文件@Testpublic void copyFromHdfsToLocal() throws URISyntaxException, IOException, InterruptedException {// boolean:是否删除源文件 //src:hdfs路径 //dst:目标路径,本地路径 fs.copyToLocalFile(true, new Path("/lagou.txt"), new Path("e:/lagou_copy.txt"));}// 删除文件或者文件夹@Testpublic void deleteFile() throws URISyntaxException, IOException, InterruptedException {fs.delete(new Path("/api_test2"), true);}// 遍历hdfs的根目录得到文件以及文件夹的信息:名称,权限,长度等@Testpublic void listFiles() throws URISyntaxException, IOException, InterruptedException {//得到一个迭代器:装有指定目录下所有文件信息 RemoteIterator remoteIterator = fs.listFiles(new Path("/"), true);//遍历迭代器 while (remoteIterator.hasNext()) {LocatedFileStatus fileStatus = remoteIterator.next();//文件名称 final String fileName = fileStatus.getPath().getName();//长度 final long len = fileStatus.getLen();//权限 final FsPermission permission = fileStatus.getPermission();//分组 final String group = fileStatus.getGroup();//用户 final String owner = fileStatus.getOwner();System.out.println(fileName + "\t" + len + "\t" + permission + "\t" + group + "\t" + owner);//块信息 final BlockLocation[] blockLocations = fileStatus.getBlockLocations();for (BlockLocation blockLocation : blockLocations) {final String[] hosts = blockLocation.getHosts();for (String host : hosts) {System.out.println("主机名称" + host);}}System.out.println("---------------------------------");}}// 文件以及文件夹判断@Testpublic void isFile() 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 @Testpublic 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);}// 下载文件@Testpublic 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文件并把内容输出两次,本质就是读取文 件内容两次并输出@Testpublic 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);}}```
上一篇:单调队列算法总结