hadoop之HDFS的API操作

1.创建maven项目

  

 

 2.引入依赖

<dependency>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-common</artifactId>
  <version>2.8.0</version>
</dependency>
<dependency>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-hdfs</artifactId>
  <version>2.8.0</version>
</dependency>
<dependency>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-client</artifactId>
  <version>2.8.0</version>
</dependency>

3.使用FileSystem API数据

  Hadoop的hdfs操作中,有个非常重要的api。就是 org.apache.hadoop.fs.FileSystem, 这是我们用户操作hdfs的直接入口,类 jdbc操作数据库的Connection

@Test
    public void testMkdir() throws URISyntaxException, IOException, InterruptedException {
        //1.配置文件
        Configuration configuration =new Configuration();
        //2.获取文件系统
        FileSystem fileSystem = FileSystem.get(URI.create("hdfs://192.168.147.11:9000"),
                configuration);

    }

4.创建文件夹

/**
     * 在HDFS中创建文件夹
     */
    @Test
    public void testMkdir() throws URISyntaxException, IOException, InterruptedException {
        //1.配置文件
        String url ="hdfs://192.168.147.11:9000";
        Configuration configuration =new Configuration();
        //2.获取文件系统
        FileSystem fileSystem = FileSystem.get(URI.create(url),
                configuration);
        //3.创建文集夹
        String path ="/zjn01";
        boolean exists = fileSystem.exists(new Path(path));
        if (!exists){
            boolean mkdirs = fileSystem.mkdirs(new Path(path));
            System.out.println("文件夹是否创建成功:"+mkdirs);
        }
    }

  注意:如果出现以下错误org.apache.hadoop.security.AccessControlException是由于我们使用windows用户远程操作位于Linux主机HDFS服务权限不足所导致的异常。需要修改master和slave节点上的hdfs-site.xml文件加入以下内容:

<property>
  <name>dfs.permissions</name>
  <value>false</value>
</property>

 

 

 

   最后运行代码效果如下:

  

 

  使用前面学到的命令查看服务器里是否创建成功

  

5.下载文件到本地

/**
     * 下载文件
     */
    @Test
    public void testCopyLocalFile() throws URISyntaxException, IOException, InterruptedException{
        //1.配置文件
        String url ="hdfs://192.168.147.11:9000";
        Configuration configuration =new Configuration();
        //2.获取文件系统
        FileSystem fileSystem = FileSystem.get(URI.create(url),
                configuration);
        fileSystem.copyToLocalFile(false,new Path("/a.txt"),
        new Path("I:"+ File.separator+"newhadoop"),true);
    }

 

 6.上传文件

/**
     * 上传文件
     * put
     */
    @Test
    public void testCopyFromLocal() throws URISyntaxException, IOException, InterruptedException{
        //1.配置文件
        String url ="hdfs://192.168.147.11:9000";
        Configuration configuration =new Configuration();
        //2.获取文件系统
        FileSystem fileSystem = FileSystem.get(URI.create(url),
                configuration);
        fileSystem.copyFromLocalFile(new Path("I:"+File.separator+"a.txt")
        ,new Path("/zjn01"));
    }

  将刚才下载下来的文件重新上传上Linux系统

 

posted @ 2020-05-13 12:11  琴昕LNS~  阅读(534)  评论(0编辑  收藏  举报