HDFSAPI应用

1. 配置windows下hadoop环境

第一步:将hadoop2.7.5文件夹拷贝到一个没有中文没有空格的路径下面

第二步:在windows上面配置hadoop的环境变量: HADOOP_HOME,并将%HADOOP_HOME%\bin添加到path中

第三步:把hadoop2.7.5文件夹中bin目录下的hadoop.dll文件放到系统盘: C:\Windows\System32 目录

第四步:关闭windows重启

2. 导入maven依赖

<dependencies>
      	<dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.7.5</version>
	    </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.7.5</version>
		</dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <version>2.7.5</version>
		</dependency>
		<dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-mapreduce-client-core</artifactId>
            <version>2.7.5</version>
		</dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <!--    <verbal>true</verbal>-->
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <minimizeJar>true</minimizeJar>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

3. 文件访问

3.1 使用URL方式访问

import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class demo1 {
    
    
    // 使用
    @Test
    public void demo1()throws  Exception{
    
    

        //第一步:注册hdfs 的url
        URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());

        //获取文件输入流
        InputStream inputStream  = new URL("hdfs://hadoop1:8020/a.txt").openStream();
        //获取文件输出流
        FileOutputStream outputStream = new FileOutputStream(new File("D:\\hello.txt"));

        //实现文件的拷贝
        IOUtils.copy(inputStream, outputStream);

        //关闭流
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}

3.2 通过文件系统访问数据(推荐使用)

3.2.1 获取Filesystem

获取FileSystem的四种方式

  • Configuration:封装了客户端或服务器的配置
  • FileSystem:文件系统,可以通过一些方法来进行文件操作
  • 方式一

    @Test
        public void getFileSystem1() throws IOException {
          
          
            //创建Configuration对象
            Configuration configuration = new Configuration();
            //指定我们使用的文件系统类型,后面的url开头如果是file则表示访问本地文件,如果是hdfs则表示访问分布式文件系统文件
            configuration.set("fs.defaultFS", "hdfs://hadoop1:8020/");
    
            //获取指定的文件系统
            FileSystem fileSystem = FileSystem.get(configuration);
            //输出filesystem
            System.out.println(fileSystem.toString());
    
        }
    

    在这里插入图片描述

  • 方式二

    @Test
    public void getFileSystem2() throws  Exception{
          
          
        //URI是统一资源标识符
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"), new Configuration());
        System.out.println("fileSystem:"+fileSystem);
    }
    

    URI是统一资源标识符,不一定指的是地址

    URL是统一资源定位符,是URI的子类,具体指资源地址信息

  • 方式三

    扫描二维码关注公众号,回复: 12793594 查看本文章
    @Test
    public void getFileSystem3() throws  Exception{
          
          
        Configuration configuration = new Configuration();
        //指定文件类型
        configuration.set("fs.defaultFS", "hdfs://hadoop1:8020");
        //获取指定文件类型
        FileSystem fileSystem = FileSystem.newInstance(configuration);
        System.out.println(fileSystem.toString());
    }
    
  • 方式四

    @Test
    //和方式二类似
    public void getFileSystem4() throws  Exception{
          
          
        FileSystem fileSystem = FileSystem.newInstance(new URI("hdfs://hadoop1:8020") ,new Configuration());
        System.out.println(fileSystem.toString());
    }
    
3.2.2 遍历HDFS中的文件
@Test
public void listMyFiles()throws Exception{
    
    
    //获取fileSystem类
    FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01: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());
        // 获取文件block信息
        BlockLocation[] blockLocations = next.getBlockLocations();
        System.out.println("block数:"+blockLocations.length);

    }
    fileSystem.close();
}
3.2.3 在HDFS上创建文件夹
@Test
public void mkdirs() throws  Exception{
    
    
    //获取filesystem
    FileSystem fileSystem = FileSystem.get(new URI("hdfs://hadoop1:8020"), new Configuration());
    //创建文件夹
    boolean mkdirs = fileSystem.mkdirs(new Path("/dir1/test"));
    System.out.println(mkdirs);
    //创建文件
    fileSystem.create(new Path("/dir1/test/a.txt"));
    //关闭filesystem
    fileSystem.close();
}

在这里插入图片描述

3.2.4 下载文件

有两种方法

@Test
public void getFileToLocal()throws  Exception{
    
    
    //获取filesystem
    FileSystem fileSystem = FileSystem.get(new URI("hdfs://hadoop1:8020"), new Configuration());
    //hdfs上文件地址
    FSDataInputStream inputStream = fileSystem.open(new Path("/user/root/dir/a.txt"));
    //本地文件地址
    FileOutputStream  outputStream = new FileOutputStream(new File("e:\\timer.txt"));
    //下载
    IOUtils.copy(inputStream,outputStream );
    //关闭流
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(outputStream);
    //关闭文件系统
    fileSystem.close();
}
3.2.5 上传文件
@Test
public void putData() throws  Exception{
    
    
    //创建文件系统
    FileSystem fileSystem = FileSystem.get(new URI("hdfs://hadoop1:8020"), new Configuration());
    //上传文件
    fileSystem.copyFromLocalFile(new Path("file:///e:\\hello.txt"),new Path("/dir1/test"));
    fileSystem.close();
}
3.2.6 小文件合并

由于 Hadoop 擅长存储大文件,因为大文件的元数据信息比较少,如果 Hadoop 集群当中有大量的小文件,那么每个小文件都需要维护一份元数据信息,会大大的增加集群管理元数据的内存压力,所以在实际工作当中,如果有必要一定要将小文件合并成大文件进行一起处理

在上传的时候合并

@Test
public void mergeFile() throws  Exception{
    
    
    //获取分布式文件系统
    FileSystem fileSystem = FileSystem.get(new URI("hdfs://hadoop1:8020"), new Configuration(),"root");
    //在HDFS根目录上创建文件(合并后的文件)
    FSDataOutputStream outputStream = fileSystem.create(new Path("/bigfile.txt"));
    //获取本地文件系统
    LocalFileSystem local = FileSystem.getLocal(new Configuration());
    //通过本地文件系统获取文件列表,生成一个集合
    FileStatus[] fileStatuses = local.listStatus(new Path("file:///E:\\input"));
    for (FileStatus fileStatus : fileStatuses) {
    
    
        //获取每一个文件的输入流
        FSDataInputStream inputStream = local.open(fileStatus.getPath());
        //复制本地输入流到outputStream
       IOUtils.copy(inputStream,outputStream);
        //关闭每一个小文件的输入流
        IOUtils.closeQuietly(inputStream);
    }
    //关闭输出流
    IOUtils.closeQuietly(outputStream);
    //关闭本地文件系统
    local.close();
    //关闭文件系统
    fileSystem.close();
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_24852439/article/details/104185566