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);
   	}
   }
   ```
内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/gitBook/p/16962048.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!