java利用hdfs api進行上傳下載操作

1.說明

最近項目中一部分大文件需要存儲到hadoop的hdfs組件中,自己本地用3臺centos7虛擬機搭建了一套集羣。本地寫點java代碼測試一下。

代碼部分改編自網絡。

  • 環境說明
    一主二僕結構。配置了SSH免密訪問。

hadoop-master
hadoop-slave01
hadoop-slave02

2.配置部分

  • 修改hosts,添加

192.168.5.128 hadoop-master
192.168.5.129 hadoop-slave01
192.168.5.130 hadoop-slave02

  • 創建maven項目,將hadoop以下2個配置文件copy到下面路徑
    在這裏插入圖片描述
  • 添加pom依賴
<dependencies>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.7.6</version>
        </dependency>

        <!--lombok用來簡化實體類:需要安裝lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

3.代碼部分

/**
 * @Description: hdfs api操作
 * @Author laoxu
 * @Date 2020/4/9 21:33
 **/
@Slf4j
public class HDFSClient {
    FileSystem fs = null;

    @Before
    public void init() throws Exception {

        // 構造一個配置參數對象,設置一個參數:我們要訪問的hdfs的URI
        // 從而FileSystem.get()方法就知道應該是去構造一個訪問hdfs文件系統的客戶端,以及hdfs的訪問地址
        // new Configuration();的時候,它就會去加載jar包中的hdfs-default.xml
        // 然後再加載classpath下的hdfs-site.xml
        Configuration conf = new Configuration();
       // conf.set("fs.defaultFS", "hdfs://hdp-node01:9000");
        /**
         * 參數優先級: 1、客戶端代碼中設置的值 2、classpath下的用戶自定義配置文件 3、然後是服務器的默認配置
         */
        // conf.set("dfs.replication", "3");

        // 獲取一個hdfs的訪問客戶端,根據參數,這個實例應該是DistributedFileSystem的實例
        // fs = FileSystem.get(conf);
        // 如果這樣去獲取,那conf裏面就可以不要配"fs.defaultFS"參數,而且,這個客戶端的身份標識已經是hadoop用戶
        fs = FileSystem.get(new URI(conf.get("fs.defaultFS")), conf, "root");

    }

    /**
     * 往hdfs上傳文件
     *
     * @throws Exception
     */
    @Test
    public void testAddFileToHdfs() throws Exception {

        // 要上傳的文件所在的本地路徑
        // Path src = new Path("d:/upload/test.png");
        Path src = new Path("d:/software/jdk-8u171-windows-x64.exe");
        // 要上傳到hdfs的目標路徑
        Path dst = new Path("/hdfs/2020");
        fs.copyFromLocalFile(src, dst);
        fs.close();
    }

    /**
     * 從hdfs中複製文件到本地文件系統
     *
     * @throws IOException
     * @throws IllegalArgumentException
     */
    @Test
    public void testDownloadFileToLocal() throws IllegalArgumentException, IOException {
        // 不刪除原文件,同時採用本地文件系統
        fs.copyToLocalFile(false, new Path("/hdfs/2020/test.txt"), new Path("d:/download"), true);
        fs.close();
    }

    @Test
    public void testMkdirAndDeleteAndRename() throws IllegalArgumentException, IOException {

        // 創建目錄
         fs.mkdirs(new Path("/order1/2020"));

        // 重命名文件或文件夾
         fs.rename(new Path("/order1"), new Path("/order"));

        // 刪除文件夾 ,如果是非空文件夾,參數2必須給值true
        // fs.delete(new Path("/order"), true);

        fs.close();

    }

    /**
     * 查看目錄信息,只顯示文件
     *
     * @throws IOException
     * @throws IllegalArgumentException
     * @throws FileNotFoundException
     */
    @Test
    public void testListFiles() throws FileNotFoundException, IllegalArgumentException, IOException {

        // 思考:爲什麼返回迭代器,而不是List之類的容器
        RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);

        while (listFiles.hasNext()) {
            LocatedFileStatus fileStatus = listFiles.next();
            System.out.println(fileStatus.getPath().getName());
            System.out.println(fileStatus.getBlockSize());
            System.out.println(fileStatus.getPermission());
            System.out.println(fileStatus.getLen());
            BlockLocation[] blockLocations = fileStatus.getBlockLocations();
            for (BlockLocation bl : blockLocations) {
                System.out.println("block-length:" + bl.getLength() + "--" + "block-offset:" + bl.getOffset());
                String[] hosts = bl.getHosts();
                for (String host : hosts) {
                    System.out.println(host);
                }
            }
            System.out.println("--------------爲angelababy打印的分割線--------------");
        }
    }

    /**
     * 查看文件及文件夾信息
     *
     * @throws IOException
     * @throws IllegalArgumentException
     * @throws FileNotFoundException
     */
    @Test
    public void testListAll() throws FileNotFoundException, IllegalArgumentException, IOException {
        FileStatus[] listStatus = fs.listStatus(new Path("/hdfs/2020"));

        System.out.println(listStatus.length);

        String flag = "文件夾:             ";
        for (FileStatus fstatus : listStatus) {
            if (fstatus.isFile())  flag = "文件:         ";
            System.out.println(flag + fstatus.getPath().getName());
        }

        fs.close();
    }
}
  • 上傳(圖)
    在這裏插入圖片描述
  • 下載(圖)
    在這裏插入圖片描述
  • 創建文件夾
    在這裏插入圖片描述

4.關於hadoop搭建

看我後續文章。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章