1.5.4 HDFS 客戶端操作-hadoop-最全最完整的保姆級的java大數據學習資料

来源:https://www.cnblogs.com/gitBook/archive/2022/12/07/16962048.html
-Advertisement-
Play Games

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

  1. 基本語法

bin/hadoop fs 具體命令 OR bin/hdfs dfs 具體命令

  1. 命令大全
[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
  1. HDFS命令演示

    1. 啟動Hadoop集群(方便後續的測試)

      [root@linux121 hadoop-2.9.2]$ sbin/start-dfs.sh
      [root@linux122 hadoop-2.9.2]$ sbin/start-yarn.sh
      
    2. -help:輸出這個命令參數

      [root@linux121 hadoop-2.9.2]$ hadoop fs -help rm
      
    3. -ls: 顯示目錄信息

      [root@linux121 hadoop-2.9.2]$ hadoop fs -ls /
      
    4. -mkdir:在HDFS上創建目錄

      [root@linux121 hadoop-2.9.2]$ hadoop fs -mkdir -p /lagou/bigdata
      
    5. -moveFromLocal:從本地剪切粘貼到HDFS

      [root@linux121 hadoop-2.9.2]$ touch hadoop.txt
      
      [root@linux121 hadoop-2.9.2]$ hadoop fs  -moveFromLocal  ./hadoop.txt /lagou/bigdata
      
    6. -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
      
    7. -cat:顯示文件內容

      [root@linux121 hadoop-2.9.2]$ hadoop fs -cat /lagou/bigdata/hadoop.txt
      
    8. -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
      
    9. -copyFromLocal:從本地文件系統中拷貝文件到HDFS路徑去

      [root@linux121 hadoop-2.9.2]$ hadoop fs -copyFromLocal README.txt /
      
    10. -copyToLocal:從HDFS拷貝到本地

      [root@linux121 hadoop-2.9.2]$ hadoop fs -copyToLocal /lagou/bigdata/hadoop.txt ./
      
    11. -cp :從HDFS的一個路徑拷貝到HDFS的另一個路徑

      [root@linux121 hadoop-2.9.2]$ hadoop fs -cp /lagou/bigdata/hadoop.txt /hdfs.txt
      
    12. -mv:在HDFS目錄中移動文件

      [root@linux121 hadoop-2.9.2]$ hadoop fs -mv /hdfs.txt /lagou/bigdata/
      
    13. -get:等同於copyToLocal,就是從HDFS下載文件到本地

      [root@linux121 hadoop-2.9.2]$ hadoop fs -get /lagou/bigdata/hadoop.txt ./
      
    14. -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/
      
    15. -tail:顯示一個文件的末尾

      [root@linux121 hadoop-2.9.2]$ hadoop fs -tail /user/root/test/yarn.txt
      
    16. -rm:刪除文件或文件夾

      [root@linux121 hadoop-2.9.2]$ hadoop fs -rm /user/root/test/yarn.txt
      
    17. -rmdir:刪除空目錄

      [root@linux121 hadoop-2.9.2]$ hadoop fs -mkdir /test
      [root@linux121 hadoop-2.9.2]$ hadoop fs -rmdir /test
      
    18. -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
      
    19. -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 客戶端環境準備
  1. 將Hadoop-2.9.2安裝包解壓到非中文路徑(例如:E:\hadoop-2.9.2)。

在這裡插入圖片描述

  1. 配置HADOOP_HOME環境變數

在這裡插入圖片描述

  1. 配置Path環境變數。

在這裡插入圖片描述

  1. 創建一個Maven工程ClientDemo

  2. 導入相應的依賴坐標+日誌配置文件

    <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
    
  3. 創建包名:com.lagou.hdfs

  4. 創建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 上傳文件
  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"); 
    }
    
  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)用戶自定義配置文件 >(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流的方式實現文件的上傳 和下載。

  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集群許可權校驗

     ```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);
   	}
   }
   ```

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 未預期的符號 `then' 附近有語法錯誤 : 行 : `then' ` if [ -f $i ];then' 未預期的符號 `done' 附近有語法錯誤 ...
  • ##指南使用操作系統:OpenEuler 22.09(網路安裝,最小安裝,使用預設源) ##指南使用系統自帶Python版本:3.10(高版本,這不是3.1喔) 1. 安裝基本的編譯環境 yum -y install gcc gcc-c++ make libtool zlib zlib-devel ...
  • 說明 參考教程:https://baijiahao.baidu.com/s?id=1662960328855347503 特別註意,最好用最新的PE工具,我用的 微PE。因為我弄過一次全盤安裝,導致整個硬碟在PE工具中的diskgenius無法識別,最終為U盤安裝最新版PE工具後可以識別。 硬碟分區 ...
  • 關鍵字union,又稱為聯合體、共用體,聯合體的聲明和結構體類似,但是它的行為方式又和結構體不同,這裡的行為方式主要指的是其在記憶體中的體現,結構體中的成員每一個占據不同的記憶體空間,而聯合體中的所有成員共用的是記憶體中相同的位置。 簡單看下區別: 1 struct MyStruct 2 { 3 doub ...
  • 博主這裡的大數據量、高併發業務處理優化基於博主線上項目實踐以及全網資料整理而來,在這裡分享給大家 一. 大數據量上傳寫入優化 線上業務後臺項目有一個消息推送的功能,通過上傳包含用戶id的文件,給指定用戶推送系統消息 1.1 如上功能描述很簡單,但是對於技術側想要做好這個功能,保證大用戶量(比如達到百 ...
  • 摘要:本文主要為大家帶來如何處理GaussDB CM服務異常問題。 本文分享自華為雲社區《【實例狀態】GaussDB CM服務異常》,作者:酷哥。 首先確認是否是虛擬機、網路故障,底層故障處理 PID文件未清理導致進程啟動失敗 問題現象 收到告警CM服務異常,查看集群狀態,CM節點顯示DOWN 問題 ...
  • 數倉分層 |分層|全稱|譯名|說明|壓縮|列式存儲|分區| |-|-|-|-|-|-|-| |ODS|Operation Data Store|原始層|原始數據|✅|❌|✅| |DIM|Dimension|維度層|合併維度表|✅|✅|✅| |DWD|Data Warehouse Detail|明細層 ...
  • 作者:李玉亮 引言 資料庫事務與大多數後端軟體開發人員的工作密不可分,本文從事務理論、事務技術、事務實踐等方面對常用的相關事務知識進行整理總結,供大家參考。 事務理論介紹 事務定義 在資料庫管理系統中,事務是單個邏輯或工作單元,有時由多個操作組成,在資料庫中以一致模式完成的邏輯處理稱為事務。一個例子 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...