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的子類,具體指資源地址信息

  • 方式三

    @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();
}

在這裏插入圖片描述

發佈了87 篇原創文章 · 獲贊 32 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章