ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

(软件idea)api操作HDFS(外加hdfs的一下命令)

2020-08-15 20:31:45  阅读:231  来源: 互联网

标签:HDFS fs Path hdfs idea hadoop FileSystem new Configuration


1、首先配置好hadoop的环境变量等内容,配置好maven然后编写一个简单的程序(他的目的是将本地的一个文件进行上传)

代码如下:

package com.atguigu.hdfsclient;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;


public class HDFSClient {
    @Test
    public void put() throws IOException, InterruptedException {
        FileSystem fileSystem= FileSystem.get(URI.create("hdfs://hadooplinux01:9000"),new Configuration(),"root");
        fileSystem.copyFromLocalFile(new Path("C:\\Users\\26301\\Desktop\\1.txt"),new Path("/"));
        fileSystem.close();
    }

}

  

运行结果如下:(可以看到已经运行成功了)

 

 

2、更加详细的代码操作如下(上传、下载、删除、修改、追加等等)

代码如下:

package com.atguigu.hdfsclient;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.junit.jupiter.api.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.Map;


public class HDFSClient {
    private FileSystem fs;
    @BeforeEach
    public void before() throws IOException, InterruptedException {
        fs=FileSystem.get(URI.create("hdfs://hadooplinux01:9000"),new Configuration(),"root");
    }
   //进行文件的下载
    @Test
    public void get() throws IOException, InterruptedException {
        //第一步是获取HDFS对象
        //获取文件系统写入参数(url模式为hdfs)
        Configuration configuration=new Configuration();//就好像和site.xml中的相关配置是一样的(这里使用默认的配置)
        configuration.setInt("dfs.replication",1);
        FileSystem fileSystem=FileSystem.get(URI.create("hdfs://hadooplinux01:9000"),configuration,"root");
        //获得到了filesystem
        /*下面是进行文件的下载操作
        * */

        fileSystem.copyToLocalFile(new Path("/1.txt"),new Path("D:\\"));
        //操作完成之后进行关闭,因为不支持并发访问
        fileSystem.close();
    }
    //进行文件的上传
    @Test
    public void put() throws IOException, InterruptedException {
        FileSystem fileSystem= FileSystem.get(URI.create("hdfs://hadooplinux01:9000"),new Configuration(),"root");
        fileSystem.copyFromLocalFile(new Path("C:\\Users\\26301\\Desktop\\1.txt"),new Path("/"));
        fileSystem.close();
    }
    //进行重命名
    @Test
    public void rename() throws IOException, InterruptedException {
        //获取文件系统
        FileSystem fileSystem= FileSystem.get(URI.create("hdfs://hadooplinux01:9000"),new Configuration(),"root");
        //进行操作
        fileSystem.copyFromLocalFile(new Path("/1.txt"),new Path("/2.txt"));
        //关闭文件系统
        fileSystem.close();
    }
    //进行删除操作
    @Test
    public void delete() throws IOException {
        boolean delete=fs.delete(new Path("/1.txt"),true);
        if (delete)
        {
            System.out.println("删除成功");
        }
        else
        {
            System.out.println("删除失败");
        }
    }
    //进行内容的追加
    @Test
    public void append() throws IOException {
        FSDataOutputStream append=fs.append(new Path("/1.txt"),1024);
        FileInputStream open=new FileInputStream("D:\\1.txt");
        //进行流拷贝(依次完成读写操作)
        IOUtils.copyBytes(open,append,1024,true);
    }
    //文件的查看
    @Test
    public  void ls() throws IOException {
        //与下面的区别是这个文件夹和问价一起查
        FileStatus[] fileStatuses=fs.listStatus(new Path("/"));
        for(FileStatus fileStatus : fileStatuses)
        {
            if (fileStatus.isFile())
            {
                System.out.println("一下信息是一个文件信息");
                System.out.println(fileStatus.getPath());
                System.out.println(fileStatus.getLen());
            }
            else
            {
                System.out.println("这是一个文件夹");
                System.out.println(fileStatus.getPath());
            }
        }
    }
    @Test
    private void listFiles() throws IOException {
        //将所有的文件列出来,对于目录进行递归(与上边的区别是只查文件不查文件夹)
        RemoteIterator<LocatedFileStatus> files=fs.listFiles(new Path("/"),true);
        while(files.hasNext())
        {
            //获取块的信息,并且查看备份的文件都在哪里
            LocatedFileStatus file=files.next();
            System.out.println("------");
            System.out.println(file.getPath());
            System.out.println("快信息");
            BlockLocation[] blockLocations=file.getBlockLocations();
            for(BlockLocation blockLocation : blockLocations)
            {
               String[] hosts=blockLocation.getHosts();
            }

        }
    }
    @AfterEach
    public void after() throws IOException {
        fs.close();
    }
}

  

部分运行结果:

 

3、零碎的知识点集合:

idea中的System.out.println()的快捷键是cout。buffersize表示的是缓冲区的大小

4、不同注释的区别:

 

 5、HDFS的相关文件操作:

将文件上传到hdfs

1.首先创建一个文本文件

#touch 创建文件 mkdir 创建文件夹
 
touch test
 
#编辑文件
 
vim test
2.可以随便输入一些内容

hello world
 
hello lilei
 
hello haimeimei
 
hello hadoop
保存退出

3.将文件上传到hdfs根目录中

#将文件上传到Hadoop根目录中
hadoop fs -put test /
#查看是否上传成功
hadoop fs -ls /
#查看文件内容,发现与之前的内容相同则上传成功
#如果你在安装虚拟机的时候没有选择中文,而在文件中有中文内容,有可能造成乱码
hadoop fs -cat /test
#hdfs上的文件是不支持修改的
如果想要上传到指定目录,直接替换根目录(/)即可

文件上传成功了,那么接下来试一试文件夹

#创建文件夹
 
mkdir testdir
 
#上传
 
hadoop fs -put testdir /
 
#查看
 
hadoop fs -ls /
删除文件/文件夹

#删除文件
 
hadoop fs -rm -f /test
 
#删除文件夹
 
hadoop fs -rm -r /testdir
 
#查看
 
hadoop fs -ls /
将hdfs上的文件下载到本地

#将文件上传上去
[root@master tmp]# hadoop fs -put test /
#将test改名为test1
[root@master tmp]# hadoop fs -mv /test /test1
#查看文件内容
[root@master tmp]# hadoop fs -cat /test1
hello world
hello lilei
hello haimeimei
hello hadoop
#文件下载
[root@master tmp]# hadoop fs -get /test1
#查看tmp文件夹下的内容
[root@master tmp]# ls
test  test1  testdir
 

  

 

 

6、更多的文件操作如下:

3.2.1 HDFS文件上传(测试参数优先级

1.编写源代码

@Test

public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException {

 

// 1 获取文件系统

Configuration configuration = new Configuration();

configuration.set("dfs.replication", "2");

FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");

 

// 2 上传文件

fs.copyFromLocalFile(new Path("e:/banzhang.txt"), new Path("/banzhang.txt"));

 

// 3 关闭资源

fs.close();

 

System.out.println("over");

}

2.将hdfs-site.xml拷贝到项目的根目录下

<?xml version="1.0" encoding="UTF-8"?>

<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

 

<configuration>

<property>

<name>dfs.replication</name>

        <value>1</value>

</property>

</configuration>

3.参数优先级

参数优先级排序:(1)客户端代码中设置的值 >(2)ClassPath下的用户自定义配置文件 >(3)然后是服务器的默认配置

3.2.2 HDFS文件下载

@Test

public void testCopyToLocalFile() throws IOException, InterruptedException, URISyntaxException{

 

// 1 获取文件系统

Configuration configuration = new Configuration();

FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");

 

// 2 执行下载操作

// boolean delSrc 指是否将原文件删除

// Path src 指要下载的文件路径

// Path dst 指将文件下载到的路径

// boolean useRawLocalFileSystem 是否开启文件校验

fs.copyToLocalFile(false, new Path("/banzhang.txt"), new Path("e:/banhua.txt"), true);

 

// 3 关闭资源

fs.close();

}

3.2.3 HDFS文件夹删除

@Test

public void testDelete() throws IOException, InterruptedException, URISyntaxException{

 

// 1 获取文件系统

Configuration configuration = new Configuration();

FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");

 

// 2 执行删除

fs.delete(new Path("/0508/"), true);

 

// 3 关闭资源

fs.close();

}

3.2.4 HDFS文件名更改

@Test

public void testRename() throws IOException, InterruptedException, URISyntaxException{

 

// 1 获取文件系统

Configuration configuration = new Configuration();

FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");

 

// 2 修改文件名称

fs.rename(new Path("/banzhang.txt"), new Path("/banhua.txt"));

 

// 3 关闭资源

fs.close();

}

3.2.5 HDFS文件详情查看

查看文件名称、权限、长度、块信息

@Test

public void testListFiles() throws IOException, InterruptedException, URISyntaxException{

 

// 1获取文件系统

Configuration configuration = new Configuration();

FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");

 

// 2 获取文件详情

RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);

 

while(listFiles.hasNext()){

LocatedFileStatus status = listFiles.next();

 

// 输出详情

// 文件名称

System.out.println(status.getPath().getName());

// 长度

System.out.println(status.getLen());

// 权限

System.out.println(status.getPermission());

// 分组

System.out.println(status.getGroup());

 

// 获取存储的块信息

BlockLocation[] blockLocations = status.getBlockLocations();

 

for (BlockLocation blockLocation : blockLocations) {

 

// 获取块存储的主机节点

String[] hosts = blockLocation.getHosts();

 

for (String host : hosts) {

System.out.println(host);

}

}

 

System.out.println("-----------班长的分割线----------");

}

 

// 3 关闭资源

fs.close();

}

3.2.6 HDFS文件和文件夹判断

@Test

public void testListStatus() throws IOException, InterruptedException, URISyntaxException{

 

// 1 获取文件配置信息

Configuration configuration = new Configuration();

FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");

 

// 2 判断是文件还是文件夹

FileStatus[] listStatus = fs.listStatus(new Path("/"));

 

for (FileStatus fileStatus : listStatus) {

 

// 如果是文件

if (fileStatus.isFile()) {

System.out.println("f:"+fileStatus.getPath().getName());

}else {

System.out.println("d:"+fileStatus.getPath().getName());

}

}

 

// 3 关闭资源

fs.close();

}

3.3 HDFS的I/O流操作

上面我们学的API操作HDFS系统都是框架封装好的。那么如果我们想自己实现上述API的操作该怎么实现呢?

我们可以采用IO流的方式实现数据的上传和下载。

3.3.1 HDFS文件上传

1.需求:把本地e盘上的banhua.txt文件上传到HDFS根目录

2.编写代码

@Test

public void putFileToHDFS() throws IOException, InterruptedException, URISyntaxException {

 

// 1 获取文件系统

Configuration configuration = new Configuration();

FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");

 

// 2 创建输入流

FileInputStream fis = new FileInputStream(new File("e:/banhua.txt"));

 

// 3 获取输出流

FSDataOutputStream fos = fs.create(new Path("/banhua.txt"));

 

// 4 流对拷

IOUtils.copyBytes(fis, fos, configuration);

 

// 5 关闭资源

IOUtils.closeStream(fos);

IOUtils.closeStream(fis);

    fs.close();

}

3.3.2 HDFS文件下载

1.需求:从HDFS上下载banhua.txt文件到本地e盘上

2.编写代码

// 文件下载

@Test

public void getFileFromHDFS() throws IOException, InterruptedException, URISyntaxException{

 

// 1 获取文件系统

Configuration configuration = new Configuration();

FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");

 

// 2 获取输入流

FSDataInputStream fis = fs.open(new Path("/banhua.txt"));

 

// 3 获取输出流

FileOutputStream fos = new FileOutputStream(new File("e:/banhua.txt"));

 

// 4 流的对拷

IOUtils.copyBytes(fis, fos, configuration);

 

// 5 关闭资源

IOUtils.closeStream(fos);

IOUtils.closeStream(fis);

fs.close();

}

3.3.3 定位文件读取

1.需求:分块读取HDFS上的大文件,比如根目录下的/hadoop-2.7.2.tar.gz

2.编写代码

(1)下载第一块

@Test

public void readFileSeek1() throws IOException, InterruptedException, URISyntaxException{

 

// 1 获取文件系统

Configuration configuration = new Configuration();

FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");

 

// 2 获取输入流

FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz"));

 

// 3 创建输出流

FileOutputStream fos = new FileOutputStream(new File("e:/hadoop-2.7.2.tar.gz.part1"));

 

// 4 流的拷贝

byte[] buf = new byte[1024];

 

for(int i =0 ; i < 1024 * 128; i++){

fis.read(buf);

fos.write(buf);

}

 

// 5关闭资源

IOUtils.closeStream(fis);

IOUtils.closeStream(fos);

fs.close();

}

(2)下载第二块

@Test

public void readFileSeek2() throws IOException, InterruptedException, URISyntaxException{

 

// 1 获取文件系统

Configuration configuration = new Configuration();

FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");

 

// 2 打开输入流

FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz"));

 

// 3 定位输入数据位置

fis.seek(1024*1024*128);

 

// 4 创建输出流

FileOutputStream fos = new FileOutputStream(new File("e:/hadoop-2.7.2.tar.gz.part2"));

 

// 5 流的对拷

IOUtils.copyBytes(fis, fos, configuration);

 

// 6 关闭资源

IOUtils.closeStream(fis);

IOUtils.closeStream(fos);

}

(3)合并文件

在Window命令窗口中进入到目录E:\,然后执行如下命令,对数据进行合并

type hadoop-2.7.2.tar.gz.part2 >> hadoop-2.7.2.tar.gz.part1

合并完成后,将hadoop-2.7.2.tar.gz.part1重新命名为hadoop-2.7.2.tar.gz。解压发现该tar包非常完整。

 

标签:HDFS,fs,Path,hdfs,idea,hadoop,FileSystem,new,Configuration
来源: https://www.cnblogs.com/dazhi151/p/13509397.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有