基于Java API操作HDFS

简介: 笔记

一、基于Maven环境构建工程


1.新建工程

2.新建工程变成maven工程

3.安装配置maven环境,编辑setting文件

4.idea工具配置maven

5.编辑pom.xml文件

<properties>
    <hadoop.version>2.6.0</hadoop.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <version>${hadoop.version}</version>
    </dependency>
</dependencies>


二、基于Java API操作HDFS配置


基于Java API对HDFS操作的初始化配置

Configuration -> FileSystem

// 初始化的配置
private FileSystem getFileSystem() throws IOException {
    Configuration configuration = new Configuration();
    FileSystem fileSystem = FileSystem.get(configuration);
    return fileSystem;
}


三、基于Java API 读取或上传HDFS文件内容


在操作之前需要两个配置文件:core-site.xml ,hdfs-site.xml

将Hadoop中这两个文件下载到resources目录下。

测试:

在hdfs上创建文件:

bin/hdfs dfs -mkdir -p /user/caizhengjie/hdfs
bin/hdfs dfs -put /opt/modules/hadoop/etc/hadoop/core-site.xml /user/caizhengjie/hdfs

读取文件:

Path -> FSDataInputStream ->IOUtils

// 读取HDFS文件
private void readHDFSFile(String filePath){
    FSDataInputStream fsDataInputStream = null;
    try {
        Path path = new Path(filePath);
        // 创建hdfs文件输入流
        fsDataInputStream = this.getFileSystem().open(path);
        // 读取数据
        IOUtils.copyBytes(fsDataInputStream,System.out,4096,false);
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (fsDataInputStream != null){
            IOUtils.closeStream(fsDataInputStream);
        }
    }
}

上传文件:

// 上传HDFS文件,需要两个参数,一个是本地文件的路径,一个是hdfs中的路径
private void writeHDFS(String localPath,String hdfsPath){
    FSDataOutputStream outputStream = null;
    FileInputStream fileInputStream = null;
    try{
        Path path = new Path(hdfsPath);
        // hdfs文件输出流
        outputStream = this.getFileSystem().create(path);
        // 本地文件输入流
        fileInputStream = new FileInputStream(localPath);
        IOUtils.copyBytes(fileInputStream,outputStream,4096,false);
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (fileInputStream != null){
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (outputStream != null){
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

总代码:

package com.kfk.hadoop.hdfs;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import java.io.FileInputStream;
import java.io.IOException;
/**
 * @author : 蔡政洁
 * @email :caizhengjie888@icloud.com
 * @date : 2020/10/7
 * @time : 5:29 下午
 */
public class HdfsAPP {
    // 初始化的配置
    private FileSystem getFileSystem() throws IOException {
        Configuration configuration = new Configuration();
        FileSystem fileSystem = FileSystem.get(configuration);
        return fileSystem;
    }
    // 读取HDFS文件
    private void readHDFSFile(String filePath){
        FSDataInputStream fsDataInputStream = null;
        try {
            Path path = new Path(filePath);
            // 创建hdfs文件输入流
            fsDataInputStream = this.getFileSystem().open(path);
            // 读取数据
            IOUtils.copyBytes(fsDataInputStream,System.out,4096,false);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fsDataInputStream != null){
                IOUtils.closeStream(fsDataInputStream);
            }
        }
    }
    // 上传HDFS文件,需要两个参数,一个是本地文件的路径,一个是hdfs中的路径
    private void writeHDFS(String localPath,String hdfsPath){
        FSDataOutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        try{
            Path path = new Path(hdfsPath);
            // hdfs文件输出流
            outputStream = this.getFileSystem().create(path);
            // 本地文件输入流
            fileInputStream = new FileInputStream(localPath);
            IOUtils.copyBytes(fileInputStream,outputStream,4096,false);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        // 读取hdfs文件的路径
        String filePath = "hdfs://bigdata-pro-m01:9000/user/caizhengjie/hdfs/core-site.xml";
        // 上传hdfs文件的路径
        String hdfsPath = "hdfs://bigdata-pro-m01:9000/user/caizhengjie/hdfs/local.xml";
        // 本地文件
        String localPath = "/Users/caizhengjie/IdeaProjects/bigdata_study/src/main/resources/hdfs-site.xml";
        HdfsAPP hdfsAPP = new HdfsAPP();
        hdfsAPP.readHDFSFile(filePath);
        hdfsAPP.writeHDFS(localPath,hdfsPath);
    }
}

运行结果:

log4j:WARN No appenders could be found for logger (org.apache.hadoop.metrics2.lib.MutableMetricsFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!--
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License. See accompanying LICENSE file.
-->
<!-- Put site-specific property overrides in this file. -->
<configuration>
  <property>
        <name>fs.defaultFS</name>
        <value>hdfs://bigdata-pro-m01:9000</value>
        </property>
        <property>
        <name>hadoop.tmp.dir</name>
        <value>/opt/modules/hadoop/tmp</value>
        </property>
        <property>
        <name>hadoop.http.staticuser.user</name>
        <value>caizhengjie</value>
        </property>
</configuration>
Process finished with exit code 0
相关文章
|
Java API 数据处理
Java新特性:使用Stream API重构你的数据处理
Java新特性:使用Stream API重构你的数据处理
|
Java 大数据 API
Java Stream API:现代集合处理与函数式编程
Java Stream API:现代集合处理与函数式编程
540 100
|
Java API 数据处理
Java Stream API:现代集合处理新方式
Java Stream API:现代集合处理新方式
501 101
|
并行计算 Java 大数据
Java Stream API:现代数据处理之道
Java Stream API:现代数据处理之道
616 101
|
安全 Java API
使用 Java 构建强大的 REST API 的四个基本技巧
本文结合探险领域案例,分享Java构建REST API的四大核心策略:统一资源命名、版本控制与自动化文档、安全防护及标准化异常处理,助力开发者打造易用、可维护、安全可靠的稳健API服务。
740 116
|
JSON Java API
【干货满满】分享京东API接口到手价,用Java语言实现
本示例使用 Java 调用京东开放平台商品价格及优惠信息 API,通过商品详情和促销接口获取到手价(含优惠券、满减等),包含签名生成、HTTP 请求及响应解析逻辑,适用于比价工具、电商系统集成等场景。
|
存储 Java API
Java Stream API:现代数据处理之道
Java Stream API:现代数据处理之道
543 188
|
存储 Java API
Java Stream API:现代数据处理之道
Java Stream API:现代数据处理之道
478 92
|
Oracle Java 关系型数据库
掌握Java Stream API:高效集合处理的利器
掌握Java Stream API:高效集合处理的利器
609 80
|
安全 Java API
Java 8 Stream API:高效集合处理的利器
Java 8 Stream API:高效集合处理的利器
525 83