1.9 HDFS 的 API 操作
1.9.1. 导入 Maven 依赖
<repositories>
        <repository>
            <id>cloudera</id>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
        </repository>
    </repositories>
    <dependencies>
      <dependency>
          <groupId>jdk.tools</groupId>
          <artifactId>jdk.tools</artifactId>
          <version>1.8</version>
          <scope>system</scope>
          <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
      </dependency>
      <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-common</artifactId>
          <version>3.0.0</version>
          <scope>provided</scope>
      </dependency>
      <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-hdfs</artifactId>
          <version>3.0.0</version>
      </dependency>
      <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-hdfs-client</artifactId>
          <version>3.0.0</version>
          <scope>provided</scope>
      </dependency>
      <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-client</artifactId>
          <version>3.0.0</version>
      </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
      </dependency>
    </dependencies>1.9.2. 概述
在 Java 中操作 HDFS, 主要涉及以下 Class:
Configuration
- 该类的对象封转了客户端或者服务器的配置
 
FileSystem
- 该类的对象是一个文件系统对象,可以用该对象的一些方法来对文件进行操作, 通过 FileSystem的静态方法 get 获得该对象
 
FileSystem fs = FileSystem.get(conf)- 
get 方法从 conf 中的一个参数 fs.defaultFS的配置值判断具体是什么类型的文件系统 - 如果我们的代码中没有指定 
fs.defaultFS, 并且工程 ClassPath下也没有给定相应的配置, conf 中的默认值就来自于 Hadoop 的Jar 包中的 core-default.xml - 默认值为 
file:///, 则获取的不是一个 DistributedFileSystem的实例, 而是一个本地文件系统的客户端对象 
1.9.3. 获取 FileSystem 的几种方式
- 第一种方式
 
@Test
    public void getFileSystem() throws URISyntaxException, IOException {
        Configuration configuration = new Configuration();
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.52.250:8020"), configuration);
        System.out.println(fileSystem.toString());
    }- 第二种方式
 
@Test
    public void getFileSystem2() throws URISyntaxException, IOException {
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS","hdfs://192.168.52.250:8020");
        FileSystem fileSystem = FileSystem.get(new URI("/"), configuration);
        System.out.println(fileSystem.toString());
    }- 第三种方式
 
@Test
    public void getFileSystem3() throws URISyntaxException, IOException {
        Configuration configuration = new Configuration();
        FileSystem fileSystem = FileSystem.newInstance(new URI("hdfs://192.168.52.250:8020"), configuration);
        System.out.println(fileSystem.toString());
    }- 第四种方式
 
@Test
    public void getFileSystem4() throws  Exception{
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS","hdfs://192.168.52.250:8020");
        FileSystem fileSystem = FileSystem.newInstance(configuration);
        System.out.println(fileSystem.toString());
    }1.9.4. 遍历 HDFS 中所有文件
- 递归遍历
 
@Test
    public void listFile() throws Exception{
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.52.100:8020"), new Configuration());
        FileStatus[] fileStatuses = fileSystem.listStatus(new Path("/"));
        for (FileStatus fileStatus : fileStatuses) {
            if(fileStatus.isDirectory()){
                Path path = fileStatus.getPath();
                listAllFiles(fileSystem,path);
            }else{
                System.out.println("文件路径为"+fileStatus.getPath().toString());
            }
        }
    }
    public void listAllFiles(FileSystem fileSystem,Path path) throws  Exception{
        FileStatus[] fileStatuses = fileSystem.listStatus(path);
        for (FileStatus fileStatus : fileStatuses) {
            if(fileStatus.isDirectory()){
                listAllFiles(fileSystem,fileStatus.getPath());
            }else{
                Path path1 = fileStatus.getPath();
                System.out.println("文件路径为"+path1);
            }
        }
    }- 使用 API 遍历
 
@Test
    public void listMyFiles()throws Exception{
        //获取fileSystem类
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.52.250:8020"), new Configuration());
        //获取RemoteIterator 得到所有的文件或者文件夹,第一个参数指定遍历的路径,第二个参数表示是否要递归遍历
        RemoteIterator<LocatedFileStatus> locatedFileStatusRemoteIterator = fileSystem.listFiles(new Path("/"), true);
        while (locatedFileStatusRemoteIterator.hasNext()){
            LocatedFileStatus next = locatedFileStatusRemoteIterator.next();
            System.out.println(next.getPath().toString());
        }
        fileSystem.close();
    }1.9.5. 下载文件到本地
@Test
    public void getFileToLocal()throws  Exception{
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.52.250:8020"), new Configuration());
        FSDataInputStream open = fileSystem.open(new Path("/test/input/install.log"));
        FileOutputStream fileOutputStream = new FileOutputStream(new File("c:\\install.log"));
        IOUtils.copy(open,fileOutputStream );
        IOUtils.closeQuietly(open);
        IOUtils.closeQuietly(fileOutputStream);
        fileSystem.close();
    }1.9.6. HDFS 上创建文件夹
@Test
    public void mkdirs() throws  Exception{
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.52.250:8020"), new Configuration());
        boolean mkdirs = fileSystem.mkdirs(new Path("/hello/mydir/test"));
        fileSystem.close();
    }1.9.7. HDFS 文件上传
@Test
    public void putData() throws  Exception{
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.52.250:8020"), new Configuration());
        fileSystem.copyFromLocalFile(new Path("file:///c:\\install.log"),new Path("/hello/mydir/test"));
        fileSystem.close();
    }1.9.8. 伪造用户
- 停止hdfs集群,在node01机器上执行以下命令
 
cd /export/servers/hadoop-3.1.1
sbin/stop-dfs.sh- 修改node01机器上的hdfs-site.xml当中的配置文件
 
cd /export/servers/hadoop-3.1.1/etc/hadoop
vim hdfs-site.xml<property>
   <name>dfs.permissions.enabled</name>
   <value>true</value>
</property>- 修改完成之后配置文件发送到其他机器上面去
 
scp hdfs-site.xml node02:$PWD
scp hdfs-site.xml node03:$PWD- 重启hdfs集群
 
cd /export/servers/hadoop-3.1.1
sbin/start-dfs.sh- 随意上传一些文件到我们hadoop集群当中准备测试使用
 
cd /export/servers/hadoop-3.1.1/etc/hadoop
hdfs dfs -mkdir /config
hdfs dfs -put *.xml /config
hdfs dfs -chmod 600 /config/core-site.xml- 使用代码准备下载文件
 
@Test
    public void getConfig()throws  Exception{
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.52.250:8020"), new Configuration(),"hadoop");
        fileSystem.copyToLocalFile(new Path("/config/core-site.xml"),new Path("file:///c:/core-site.xml"));
        fileSystem.close();
    }1.9.9. 小文件合并
由于 Hadoop 擅长存储大文件,因为大文件的元数据信息比较少,如果 Hadoop集群当中有大量的小文件,那么每个小文件都需要维护一份元数据信息,会大大的增加集群管理元数据的内存压力,所以在实际工作当中,如果有必要一定要将小文件合并成大文件进行一起处理
在我们的 HDFS 的 Shell 命令模式下,可以通过命令行将很多的 hdfs文件合并成一个大文件下载到本地
cd /export/servers
hdfs dfs -getmerge /config/*.xml ./hello.xml既然可以在下载的时候将这些小文件合并成一个大文件一起下载,那么肯定就可以在上传的时候将小文件合并到一个大文件里面去
@Test
    public void mergeFile() throws  Exception{
        //获取分布式文件系统
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.52.250:8020"), new Configuration(),"hadoop");
        FSDataOutputStream outputStream = fileSystem.create(new Path("/bigfile.xml"));
        //获取本地文件系统
        LocalFileSystem local = FileSystem.getLocal(new Configuration());
        //通过本地文件系统获取文件列表,为一个集合
        FileStatus[] fileStatuses = local.listStatus(new Path("file:///F:\\传智播客大数据离线阶段课程资料\\3、大数据离线第三天\\上传小文件合并"));
        for (FileStatus fileStatus : fileStatuses) {
            FSDataInputStream inputStream = local.open(fileStatus.getPath());
            IOUtils.copy(inputStream,outputStream);
            IOUtils.closeQuietly(inputStream);
        }
        IOUtils.closeQuietly(outputStream);
        local.close();
        fileSystem.close();
    }









