Hadoop API 操作

本文介绍了如何在Hadoop中使用FileSystem API进行文件系统的基本操作,包括创建、删除文件夹及文件,遍历HDFS中的文件,以及文件的上传和下载等。同时,还提供了多种获取FileSystem实例的方法。

导入依赖

     <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>3.1.3</version>
        </dependency>

获取FileSystem的四种方式

 /**
     * Configuration   该类的对象封装了客户端或者服务器的配置
     * FileSystem 该类的对象是一个文件系统对象,可以使用该类对象的一些方法来对文件进行操作,通过FileSyatem
     * 的静态方法get获得该对象
     **/
    //获取FileSystem的集中类型
    //第一种
    @Test
    public void FileSystemdemo01() throws IOException {
        Configuration configuration = new Configuration();
        //指定使用的文件系统类型
        //fs.defaultFS 固定不变的参数
        configuration.set("fs.defaultFS", "hdfs://node01:8020/");
        //获取指定的文件系统
        //导包注意 import org.apache.hadoop.fs
        FileSystem fileSystem = FileSystem.get(configuration);
        System.out.println("demo01-->" + fileSystem);
    }

    //第二种
    @Test
    public void FileSystemdemo02() throws Exception {
        FileSystem fileSystem = FileSystem.get(
                new URI("hdfs://node01:8020")
                , new Configuration()
        );
        System.out.println("demo02-->" + fileSystem);
    }

    //第三种
    @Test
    public void FileSystemdemo03() throws IOException {
        Configuration configuration = new Configuration();
        //指定文件系统
        configuration.set("fa.defaultFS", "hdfs://node01:8020");
        //创阿FileSystem的实列
        FileSystem fileSystem = FileSystem.newInstance(configuration);
        System.out.println("demo03-->" + fileSystem.toString());
    }

    //地四种
    @Test
    public void FileSystemdemo04() throws Exception {
        FileSystem fileSystem = FileSystem.newInstance(
                new URI("hdfs://node01:8020")
                , new Configuration());
        System.out.println("demo04-->" + fileSystem);
    }

使用url访问数据

//1.错误1

    /**
     * 是maven加载hadoop的依赖包之后,启动项目出现了以上异常
     * 这个异常是jar包的冲突,删除掉slf4j-log4j12-1.7.26.jar就可以了
     * 我们在maven依赖中对hadoop-hdfs和hadoop-client的依赖都去除slf4j-log4j12依赖即可
     */
    @Test  //使用url方式访问数据
    public void demo01() throws IOException {
        //1.注册hdfs的url
        URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
        //2.获取文件输入流
        InputStream inputStream = new URL("hdfs://node01:8020/dir1/a.txt").openStream();
        //3.获取文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(new File("D:/a.txt"));
        //4.实现文件的拷贝
        IOUtils.copy(inputStream, fileOutputStream);
        //5.关闭流
        System.out.println("完成");
        org.apache.commons.io.IOUtils.closeQuietly(inputStream);
        org.apache.commons.io.IOUtils.closeQuietly(fileOutputStream);

    }

HADOOP API 操作

    //遍历hdfs中的所有文件
    @Test
    public void mylistFile() throws Exception {
        //获取FileSystem
        FileSystem fileSystem = FileSystem.newInstance(
                new URI("hdfs://node01:8020"),
                new Configuration());
        //获取RemoteIterator(迭代器) 得到所有的文件夹 第一个参数指定要遍历的路径,第二参数指定是否递归遍历
        RemoteIterator<LocatedFileStatus> fileStatusRemoteIterator =
                fileSystem.listFiles(new Path("/"), true);
        while (fileStatusRemoteIterator.hasNext()) {
            //获取文件
            LocatedFileStatus next = fileStatusRemoteIterator.next();
            //获取block信息
            BlockLocation[] blockLocations = next.getBlockLocations();
            System.out.println("block数量-->" + blockLocations.length);
            System.out.println("获取文件名字-->" + next.getPath().getName());
            System.out.println("获取文件路径-->" + next.getPath().toString());
        }
        //关闭
        fileSystem.close();
    }


    //hdfs创建文件夹
    @Test
    public void mkdirdemo() throws Exception {
        FileSystem fileSystem = FileSystem.newInstance(
                new URI("hdfs://node01:8020"),
                new Configuration());
        boolean mkdirs = fileSystem.mkdirs(new Path("/aa/bb/cc"));
        FSDataOutputStream fsDataOutputStream = fileSystem.create(new Path("/aa/bb/cc/a.txt"));
        if (mkdirs) {
            System.out.println("创建成功");
        }
        fileSystem.close();
    }


    @Test//创建文件
    public void mkdirdemo01() throws Exception {
        FileSystem fileSystem = FileSystem.newInstance(
                new URI("hdfs://node01:8020"),
                new Configuration());
        //如果输入的路径不存在也会自动创建
        fileSystem.create(new Path("/aa/bb/cc/a.txt"));
        fileSystem.close();
    }


    @Test//删除文件或文件夹
    public void deletefileandwjj() throws Exception {
        FileSystem fileSystem = FileSystem.newInstance(
                new URI("hdfs://node01:8020"),
                new Configuration());
        //删除(删除路径最后面的文件或者文件夹)
        fileSystem.deleteOnExit(new Path("/aa/bb/cc"));
        fileSystem.close();
    }

    //文件的下载
    @Test
    public void FileToLocal() throws URISyntaxException, IOException {
        FileSystem fileSystem = FileSystem.newInstance(
                new URI("hdfs://node01:8020")
                , new Configuration());
        //路径是hadoop的路径 通过filesystem的open方法
        FSDataInputStream open = fileSystem.open(new Path("/aa/bb/a.txt"));
         //上传到本地
        FileOutputStream fileOutputStream =new FileOutputStream(new File("D:/aa.txt"));
         //一边读取一边上传
        IOUtils.copy(open,fileOutputStream);
        //关闭流
        org.apache.commons.io.IOUtils.closeQuietly(open);
        org.apache.commons.io.IOUtils.closeQuietly(fileOutputStream);
        //关闭filesystem
        fileSystem.close();
    }


    //文件下载方法二
    @Test
    public void  FileToLocal02() throws URISyntaxException, IOException {
        FileSystem fileSystem = FileSystem.newInstance(
                new URI("hdfs://node01:8020")
                , new Configuration());
        fileSystem.copyToLocalFile(new Path("/aa/bb/a.txt"),new Path("D:/bb.txt"));
        fileSystem.close();
    }

    //本地文件上传到hadoop
    @Test
    public  void  LocalToFile() throws URISyntaxException, IOException {
        FileSystem fileSystem = FileSystem.newInstance(
                new URI("hdfs://node01:8020")
                , new Configuration());
        fileSystem.copyFromLocalFile(new Path("file:///D:/abc.txt"),new Path("/aa"));
        fileSystem.close();
    }
Python操作Hadoop API有多种方法,以下为具体介绍及示例: - **使用Pig和Hive**:Pig和Hive是Hadoop上的高级抽象层,Python可通过命令行调用Pig或Hive脚本来执行复杂的ETL任务。例如在Python中使用`subprocess`模块调用Hive脚本: ```python import subprocess # 执行Hive脚本 hive_script = "SELECT * FROM your_table;" process = subprocess.Popen(['hive', '-e', hive_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode == 0: print("Hive query executed successfully:") print(stdout.decode()) else: print("Error executing Hive query:") print(stderr.decode()) ``` - **使用Pydoop**:Pydoop是基于Python的库,提供对Hadoop的直接访问接口,支持HDFS文件操作以及自定义的MapReduce作业。以下是一个简单的Pydoop示例,用于统计文本文件中单词的数量: ```python import pydoop.mapreduce.api as api import pydoop.mapreduce.pipes as pipes class Mapper(api.Mapper): def map(self, context): for word in context.value.split(): context.emit(word, 1) class Reducer(api.Reducer): def reduce(self, context): s = sum(context.values) context.emit(context.key, s) def __main__(): factory = pipes.Factory(Mapper, Reducer) pipes.run_task(factory) ``` 可在命令行中使用`pydoop submit`命令运行这个MapReduce作业。 - **使用PySpark**:Spark是快速、通用的大数据分析引擎,支持多种编程语言,包括Python。通过PySpark,开发者能在Python中使用Spark的分布式计算能力。以下是一个简单的PySpark示例,用于统计文本文件中单词的数量: ```python from pyspark.sql import SparkSession # 创建SparkSession spark = SparkSession.builder \ .appName("WordCount") \ .getOrCreate() # 读取文本文件 text_file = spark.sparkContext.textFile("hdfs://your_hdfs_path/your_file.txt") # 统计单词数量 counts = text_file.flatMap(lambda line: line.split(" ")) \ .map(lambda word: (word, 1)) \ .reduceByKey(lambda a, b: a + b) # 输出结果 counts.saveAsTextFile("hdfs://your_hdfs_path/output") # 停止SparkSession spark.stop() ``` - **使用RESTful API**:Hadoop提供RESTful API,Python可使用`requests`库发送HTTP请求,间接控制Hadoop集群。例如获取HDFS文件信息: ```python import requests # HDFS Namenode的REST API地址 hdfs_namenode_url = "http://your_namenode_host:50070/webhdfs/v1" file_path = "/user/hadoop/your_file.txt" # 构建请求URL url = f"{hdfs_namenode_url}{file_path}?op=GETFILESTATUS" # 发送HTTP请求 response = requests.get(url) if response.status_code == 200: print("File status:") print(response.json()) else: print("Error getting file status:") print(response.text) ``` - **使用hadoop - yarn - api - python - client**:该库用于与Apache Hadoop® YARN API进行交互,开发者可在Python环境中管理和监控Hadoop YARN集群。示例代码可参考其官方文档进行安装和使用 [^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

热心市民爱抽烟屁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值