【Hadoop】:HDFS调用Java API进行操作

一.程序的架构

一般来讲我们可以使用命令行在linux下对HDFS进行操作,那么我们也可以使用Java对HDFS进行操作,因为一旦使用了Java,我们可以编写Java程序定时对HDFS进行操作,这样就会更加的自动,也就不需要人为在linux下输入这些命令了。这里我使用了Junit的Java单元测试对下面的API进行调用。

大致的代码结构是这样的:

@before
public void before()
{
//编写运行单元测试前需要运行的代码
}

@Test
public void test()
{
//进行单元测试时的代码,每一个函数里仅编写一个调用HDFS的Java API,
}

@After
public void after()
{
//在每一个单元测试完成之后,都会运行的代码部分
}

 

二.代码使用

调用各种API的代码如下;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FilterFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.URI;

public class hdfs_test {

    private FileSystem fileSystem;
    //现在使用before,直接就可以创建对象
    @Before
    public void before() throws Exception
    {
      //其中19000端口是我设置的,在xml文件里进行配置,你用的什么端口就使用什么,我之类用的是19000 fileSystem
=FileSystem.get(URI.create("hdfs://127.0.0.1:19000"),new Configuration()); } //现在尝试了put方法,将本地的文件上传至HDFS @Test public void put() throws IOException,InterruptedException { fileSystem.copyFromLocalFile(new Path("d:\\2.txt"),new Path("/")); } //现在来尝试一下rename方法,这个API运行起来也十分简单,可以对文件进行重命名 @Test public void rename() throws IOException, InterruptedException { fileSystem.rename(new Path("/2.txt"),new Path("/great.txt")); } //现在尝试一下delete方法,使用这个方法可以删除文件 @Test public void delete() throws IOException { fileSystem.delete(new Path("1.txt"),true); } @Test public void ls() throws Exception { FileStatus[] fileStatuses=fileSystem.listStatus(new Path("/")); for(FileStatus fileStatu: fileStatuses) if(fileStatu.isFile()) { System.out.println("这是一个文件!"); System.out.println("路径:"+fileStatu.getPath()); System.out.println("文件大小:"+fileStatu.getLen()); System.out.println(); } else { System.out.println("这是一个文件夹!"); System.out.println("路径:"+fileStatu.getPath()); System.out.println("文件大小:"+fileStatu.getLen()); System.out.println(); } } @After public void after() throws Exception { fileSystem.close(); } }

 

posted @ 2021-01-05 11:20  Geeksongs  阅读(468)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.