1.5.4 HDFS 客戶端操作 1.5.4.1 Shell 命令行操作HDFS 基本語法 bin/hadoop fs 具體命令 OR bin/hdfs dfs 具體命令 命令大全 [root@linux121 hadoop-2.9.2]# bin/hdfs dfs Usage: hadoop ...
目錄
1.5.4 HDFS 客戶端操作
1.5.4.1 Shell 命令行操作HDFS
- 基本語法
bin/hadoop fs 具體命令 OR bin/hdfs dfs 具體命令
- 命令大全
[root@linux121 hadoop-2.9.2]# bin/hdfs dfs
Usage: hadoop fs [generic options]
[-appendToFile <localsrc> ... <dst>]
[-cat [-ignoreCrc] <src> ...]
[-checksum <src> ...]
[-chgrp [-R] GROUP PATH...]
[-chmod [-R] <MODE[,MODE]... | OCTALMODE> PATH...]
[-chown [-R] [OWNER][:[GROUP]] PATH...]
[-copyFromLocal [-f] [-p] [-l] [-d] <localsrc> ... <dst>]
[-copyToLocal [-f] [-p] [-ignoreCrc] [-crc] <src> ... <localdst>] [-count [-q] [-h] [-v] [-t [<storage type>]] [-u] [-x] <path> ...] [-cp [-f] [-p | -p[topax]] [-d] <src> ... <dst>]
[-createSnapshot <snapshotDir> [<snapshotName>]]
[-deleteSnapshot <snapshotDir> <snapshotName>]
[-df [-h] [<path> ...]]
[-du [-s] [-h] [-x] <path> ...]
[-expunge]
[-find <path> ... <expression> ...]
[-get [-f] [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]
[-getfacl [-R] <path>]
[-getfattr [-R] {-n name | -d} [-e en] <path>]
[-getmerge [-nl] [-skip-empty-file] <src> <localdst>]
[-help [cmd ...]]
[-ls [-C] [-d] [-h] [-q] [-R] [-t] [-S] [-r] [-u] [<path> ...]]
[-mkdir [-p] <path> ...]
[-moveFromLocal <localsrc> ... <dst>]
[-moveToLocal <src> <localdst>]
[-mv <src> ... <dst>]
[-put [-f] [-p] [-l] [-d] <localsrc> ... <dst>]
[-renameSnapshot <snapshotDir> <oldName> <newName>]
[-rm [-f] [-r|-R] [-skipTrash] [-safely] <src> ...]
[-rmdir [--ignore-fail-on-non-empty] <dir> ...]
[-setfacl [-R] [{-b|-k} {-m|-x <acl_spec>} <path>]|[--set <acl_spec>
<path>]]
[-setfattr {-n name [-v value] | -x name} <path>]
[-setrep [-R] [-w] <rep> <path> ...]
[-stat [format] <path> ...]
[-tail [-f] <file>]
[-test -[defsz] <path>]
[-text [-ignoreCrc] <src> ...]
[-touchz <path> ...]
[-truncate [-w] <length> <path> ...]
[-usage [cmd ...]]
Generic options supported are:
-conf <configuration file> specify an application configuration file
-D <property=value> define a value for a given property
-fs <file:///|hdfs://namenode:port> specify default filesystem URL to use, overrides 'fs.defaultFS' property from configurations.
-jt <local|resourcemanager:port> specify a ResourceManager
-files <file1,...> specify a comma-separated list of files to be copied to the map reduce cluster
-libjars <jar1,...> specify a comma-separated list of jar files to be included in the classpath
-archives <archive1,...> 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。 -
1.5.4.2 JAVA客戶端
1.5.4.2.1 客戶端環境準備
- 將Hadoop-2.9.2安裝包解壓到非中文路徑(例如:E:\hadoop-2.9.2)。
- 配置HADOOP_HOME環境變數
- 配置Path環境變數。
-
創建一個Maven工程ClientDemo
-
導入相應的依賴坐標+日誌配置文件
<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
-
創建包名: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集群的用戶信息,預設是獲取當前操作系統的用戶信息,出現許可權被拒絕的問 題,報錯如下:
1.5.4.2.2 HDFS的API操作
1.5.4.2.2.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)伺服器的預設配置
1.5.4.2.2.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();
}
1.5.4.2.2.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();
}
1.5.4.2.2.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();
}
1.5.4.2.2.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();
1.5.4.2.2.6 I/O流操作HDFS
以上我們使用的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); } }
註意
- 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集群許可權校驗
```properties
vim hdfs-site.xml
#添加如下屬性
<property>
<name>dfs.permissions</name>
<value>true</value>
</property>
```
修改完成之後要分發到其它節點,同時要重啟HDFS集群
- 基於HDFS許可權本身比較雞肋的特點,我們可以徹底放棄HDFS的許可權校驗,如果生產環境中我們可以考慮藉助kerberos以及sentry等安全框架來管理大數據集群安全。所以我們直接修改HDFS的根目錄許可權為777
```shell
hadoop fs -chmod -R 777 /
```
參考代碼
```java
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 {
// boolean:是否刪除源文件
//src:hdfs路徑
//dst:目標路徑,本地路徑
fs.copyToLocalFile(true, new Path("/lagou.txt"), new Path("e:/lagou_copy.txt"));
}
// 刪除文件或者文件夾
@Test
public void deleteFile() throws URISyntaxException, IOException, InterruptedException {
fs.delete(new Path("/api_test2"), true);
}
// 遍歷hdfs的根目錄得到文件以及文件夾的信息:名稱,許可權,長度等
@Test
public void listFiles() throws URISyntaxException, IOException, InterruptedException {
//得到一個迭代器:裝有指定目錄下所有文件信息
RemoteIterator<LocatedFileStatus> 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("---------------------------------");
}
}
// 文件以及文件夾判斷
@Test
public 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
@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);
}
}
```