1、背景

在上一节中,咱们简略学习了在命令行上如何操作hdfs shell api,此处咱们通过java程序来操作一下。

2、环境筹备

  1. 须要在本地环境变量中 配置 HADOOP_HOME 或在程序启动的时候通过命令行指定hadoop.home.dir的值,值为HADOOP的home目录地址。可通过org.apache.hadoop.util.Shell#checkHadoopHome办法验证。
  2. 咱们的HADOOP最好是本人在本地零碎进行从新编译,不然可能运行局部java api会呈现问题。

3、环境搭建

3.1 引入jar包

<dependencyManagement>    <dependencies>        <dependency>            <groupId>org.junit</groupId>            <artifactId>junit-bom</artifactId>            <version>5.7.1</version>            <type>pom</type>            <scope>import</scope>        </dependency>    </dependencies></dependencyManagement><dependencies>    <dependency>        <groupId>org.apache.hadoop</groupId>        <artifactId>hadoop-client</artifactId>        <version>3.3.4</version>    </dependency>    <dependency>        <groupId>org.junit.jupiter</groupId>        <artifactId>junit-jupiter</artifactId>        <scope>test</scope>    </dependency>    <dependency>        <groupId>org.apache.logging.log4j</groupId>        <artifactId>log4j-api</artifactId>        <version>2.14.1</version>    </dependency>    <dependency>        <groupId>org.apache.logging.log4j</groupId>        <artifactId>log4j-core</artifactId>        <version>2.14.1</version>    </dependency></dependencies>

3.2 引入log4j.properties配置文件

log4j.appender.console = org.apache.log4j.ConsoleAppenderlog4j.appender.console.Target = System.outlog4j.appender.console.layout = org.apache.log4j.PatternLayoutlog4j.appender.console.layout.ConversionPattern = [%-5p] %d{ HH:mm:ss,SSS} [%t]:%m%nlog4j.rootLogger = debug,console

引入这个配置是为了,当hadoop报错时,更好的排查问题

3.3 初始化Hadoop Api

@TestInstance(TestInstance.Lifecycle.PER_CLASS)class HdfsApiTest {    private FileSystem fileSystem;    private static final Logger log = LoggerFactory.getLogger(HdfsApiTest.class);    @BeforeAll    public void setUp() throws IOException, InterruptedException {        // 1、将 HADOOP_HOME 设置到环境变量中        Configuration configuration = new Configuration();        // 2、此处的地址是 NameNode 的地址        URI uri = URI.create("hdfs://192.168.121.140:8020");        // 3、设置用户        String user = "hadoopdeploy";        // 此处如果不设置第三个参数,指的是客户端的身份,默认获取的是以后用户,不过以后用户不肯定有权限,须要指定一个有权限的用户        fileSystem = FileSystem.get(uri, configuration, user);    }    @AfterAll    public void tearDown() throws IOException {        if (null != fileSystem) {            fileSystem.close();        }    }}

此处咱们须要留神的是,须要设置客户端操作的 用户,默认状况下获取的是以后登录用户,否则很有可能会呈现如下谬误


解决办法:
1、批改目录的拜访权限。
2、批改客户端的用户,比方此处批改成hadoopdeploy

4、java api操作

4.1 创立目录

@Test@DisplayName("创立hdfs目录")public void testMkdir() throws IOException {    Path path = new Path("/bigdata/hadoop/hdfs");    if (fileSystem.exists(path)) {        log.info("目录 /bigdata/hadoop/hdfs 曾经存在,不在创立");        return;    }    boolean success = fileSystem.mkdirs(path);    log.info("创立目录 /bigdata/hadoop/hdfs 胜利:[{}?]", success);}

4.2 上传文件

@Test@DisplayName("上传文件") void uploadFile() throws IOException {     /**      * delSrc: 文件上传后,是否删除源文件 true:删除 false:不删除      * overwrite: 如果指标文件存在是否重写 true:重写 false:不重写      * 第三个参数:须要上传的文件      * 第四个参数:指标文件      */     fileSystem.copyFromLocalFile(false, true,             new Path("/Users/huan/code/IdeaProjects/me/spring-cloud-parent/hadoop/hdfs-api/src/test/java/com/huan/hadoop/HdfsApiTest.java"),             new Path("/bigdata/hadoop/hdfs")); }

4.3 列出目录下有哪些文件

@Test@DisplayName("列出目录下有哪些文件") void testListFile() throws IOException {     RemoteIterator<LocatedFileStatus> iterator = fileSystem.listFiles(new Path("/bigdata"), true);     while (iterator.hasNext()) {         LocatedFileStatus locatedFileStatus = iterator.next();         Path path = locatedFileStatus.getPath();         if (locatedFileStatus.isFile()) {             log.info("获取到文件: {}", path.getName());         }     } }

4.4 下载文件

@Test@DisplayName("下载文件") void testDownloadFile() throws IOException {     fileSystem.copyToLocalFile(false, new Path("/bigdata/hadoop/hdfs/HdfsApiTest.java"),             new Path("/Users/huan/HdfsApiTest.java"), true); }

4.5 删除文件

@Test@DisplayName("删除文件")public void testDeleteFile() throws IOException {    fileSystem.delete(new Path("/bigdata/hadoop/hdfs/HdfsApiTest.java"), false);}

4.6 检测文件是否存在

@Test@DisplayName("查看文件是否存在") public void testFileExists() throws IOException {     Path path = new Path("/bigdata/hadoop/hdfs/HdfsApiTest.java");     boolean exists = fileSystem.exists(path);     log.info("/bigdata/hadoop/hdfs/HdfsApiTest.java 存在:[{}]", exists); }

5、残缺代码

https://gitee.com/huan1993/spring-cloud-parent/blob/master/hadoop/hdfs-api/src/test/java/com/huan/hadoop/HdfsApiTest.java