HdfsAPI

本文档详细介绍了如何使用HDFS Java API进行文件创建、删除、上传下载、遍历及文件操作,涵盖了mkdirs、deleteDir、copyFromLocal、copyToLocal、listFiles和listStatus等核心功能。
摘要由CSDN通过智能技术生成

HDFS常用API

package com.ithhs;

import junit.framework.TestCase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.*;
import java.util.Arrays;

public class HDFSJavaApiDemoTest {
    FileSystem fs = null;

    /**
     * 在被测试方法之前执行,一般来说会在这里进行初始化工作,也是只会运行一次
     */
    @Before
    public void init() throws IOException {
        //设置当前用户为root用户
        System.setProperty("HADOOP_USER_NAME", "root");
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS", "hdfs://mini1:9000");
        //创建客户端对象
        fs = FileSystem.get(configuration);
    }
	
    //创建文件夹
    @Test
    public void testMkDirs() throws IOException {
        //在hdfs上创建文件夹
        Path path = new Path("/test2");
        boolean isSuccess = fs.mkdirs(path);
        //断言
        Assert.assertEquals(true, isSuccess);
    }
	
    //删除文件或文件夹
    @Test
    public void testDeleteDir() throws IOException {
        /**
         * boolean delete(Path f, boolean recursive)
         * Path f: 需要删除的文件或文件夹的路径
         * boolean recursive:是否需要递归删除,
         */
        boolean isDelete = fs.delete(new Path("/test2"), true);
        //断言
        Assert.assertEquals(true, isDelete);
    }

    //上传一个文件到hdfs上
    @Test
    public void testCopyFromLocal() throws IOException {
        /**
         * void copyFromLocalFile(Path src, Path dst)
         * Path src:本地路径
         *Path dst:hdfs路径
         */
        fs.copyFromLocalFile(new Path("e:/user.txt"), new Path("/user.txt"));
    }

	//从hdfs上下载一个文件到本地
    @Test
    public void testCopyToLocal() throws IOException {
        /**
         * void copyToLocalFile(Path src, Path dst)
         * Path src:hdfs的路径
         * Path dst:代表本地路径
         */
        fs.copyToLocalFile(new Path("/user.txt"), new Path("e:/u.txt"));
    }

    /**
     * 遍历更目录下的所有文件
     * listFiles此方法只会显示遍历到的文件,不会显示文件夹,支持递归
     */
    @Test
    public void testListFiles() throws IOException {
        /**
         * RemoteIterator<LocatedFileStatus> listFiles(final Path f, final
         boolean recursive)
         * final Path f:需要遍历的路径
         * final boolean recursive:是否递归遍历
         *
         * listFiles此方法只会显示遍历到的文件,不会显示文件夹
         */
        RemoteIterator<LocatedFileStatus> remoteIterator = fs.listFiles(new Path("/"), true);
        while (remoteIterator.hasNext()) {//判断是否有下一个元素
            //LocatedFileStatus 代表的是一个文件的描述信息
            LocatedFileStatus fileStatus = remoteIterator.next();//取出下一个元素,并将指针往后移动一位
            System.out.println("文件路径:" + fileStatus.getPath());
            System.out.println("文件名称:" + fileStatus.getPath().getName());
            System.out.println("文件的长度:" + fileStatus.getLen());
            System.out.println("文件块大小:" + fileStatus.getBlockSize());
            System.out.println("文件副本:" + fileStatus.getReplication());
            System.out.println("文件块信息:" + Arrays.toString(fileStatus.getBlockLocations()));
            System.out.println("=====================================");
        }
    }

    /**
     * 遍历一个目录,此方法会将目录也会显示出来,此方法不支持递归
     *
     * @throws IOException
     */
    @Test
    public void testListStatus() throws IOException {
        /**
         *
         * FileStatus[] listStatus(Path f) 此方法内有递归选项
         * Path f:代表的是要遍历的路径
         */
        FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
        for (FileStatus fileStatus : fileStatuses) {
        //判断遍历到的对象是文件还是文件夹
            if (fileStatus.isDirectory()) {
                System.out.println("是一个目录");
            } else {
                System.out.println("是一个文件");
            }
            System.out.println("文件路径:" + fileStatus.getPath());
            System.out.println("文件名称:" + fileStatus.getPath().getName());
            System.out.println("文件的长度:" + fileStatus.getLen());
            System.out.println("文件块大小:" + fileStatus.getBlockSize());
            System.out.println("文件副本:" + fileStatus.getReplication());
            System.out.println("=====================================");
        }
    }

    /**
     * 向hdfs上创建一个文件并且写入数据
     */
    @Test
    public void testCreate() throws IOException {
        /**
         * create(Path f, boolean overwrite)
         * Path f:文件路径
         * boolean overwrite:是否该重写该文件
         * true: 不论hdfs上是否有该文件,都会覆盖重写
         * false: 当hdfs上存在改文件,会抛出异常。不成在则创建该文件,并写入数据
         */
        //本质是一个字节输出流
        FSDataOutputStream fsDataOutputStream = fs.create(new
        Path("/out.txt"), true);
        for (int i = 0; i < 10; i++) {
        fsDataOutputStream.write("hello world".getBytes());
        fsDataOutputStream.write("\r\n".getBytes());
        }
        fsDataOutputStream.close();
    }

    /**
     * 读取hdfs上文件中的数据
     *
     * @throws IOException
     */
    @Test
    public void testRead() throws IOException {
        //FSDataInputStream 本质上是一个字节输入流
        FSDataInputStream fsDataInputStream = fs.open(new
        Path("/out2.txt"));
        int readNum = 0;//读取到的有效字节数
        byte[] bytes = new byte[1024];//每次最多读取1024个字节
        while ((readNum = fsDataInputStream.read(bytes)) != -1) {
        System.out.println(new String(bytes, 0, readNum));
        }
        fsDataInputStream.close();
    }

    /**
     * 在被测试方法运行结束之后运行的方法,只会运行一次
     */
    @After
    public void destroy() throws IOException {
        //客户端对象用完后需要关闭
        fs.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值