Java实现本地与HDFS之间的上传与下载初(Linux)

这篇博客介绍了如何在Java中实现本地文件到HDFS的上传以及从HDFS下载文件。首先确保Hadoop环境配置正确并启动HDFS。接着,引入相关Hadoop的Maven依赖,编写Java代码实现上传和下载功能。最后,将编译好的jar包部署到Linux上的Hadoop目录,通过hadoop命令执行文件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 前提构建好hadoop,并启动hdfs(hadoop)
    在这里插入图片描述
  • 导入相对应的jar包:
    本文通过maven打jar包实现需要的包主要为以下三个
    https://mvnrepository.com/search?q=hadoop
    在这里插入图片描述

java编写demo

  • 本地上传hdfs
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.FileInputStream;
import java.io.IOException;

public class Uploading {
    public static void uploading(String hdfsFile,String hdfsURL,String fileName) throws IOException {
        Configuration cfg=new Configuration();
        cfg.set("fs.defaultFS",hdfsURL);
        FileSystem fs=FileSystem.get(cfg);
        if (fs.exists(new Path(hdfsFile))){
            FSDataOutputStream fsdos=fs.create(new Path(hdfsFile));
            FileInputStream fis=new FileInputStream(fileName);
            byte[]bytes=new byte[2048];
            int count =fis.read(bytes,0,2048);
            while(count>0){
                fsdos.write(bytes,0,count);
                count=fis.read(bytes,0,2048);
            }
            fis.close();
            fsdos.close();
            fs.close();
        }
    }

    public static void main(String[] args) throws IOException {
        uploading(args[0],args[1],args[2]);
    }
}
  • 从hdfs中下载
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.FileOutputStream;
import java.io.IOException;

public class Download {
    public static void download(String hdfsFile,String hdfsURL,String fileName) throws IOException {
        Configuration cfg=new Configuration();
        cfg.set("fs.defaultFS",hdfsURL);
        FileSystem fs=FileSystem.get(cfg);
        if (fs.exists(new Path(hdfsFile))){
            FSDataInputStream fsdis=fs.open(new Path(hdfsFile));
            FileOutputStream fos=new FileOutputStream(fileName);
            byte[]bytes=new byte[2048];
            //首次读
            int count =fsdis.read(bytes,0,2048);
            while(count>0){
                fos.write(bytes,0,count);
                count=fsdis.read(bytes,0,2048);
            }
            fos.close();
            fsdis.close();
            fs.close();
        }
    }

    public static void main(String[] args) throws IOException {
        download(args[0],args[1],args[2]);
    }
  • 打jar包

在这里插入图片描述

  • 将jar包导入Linux ,hadoop目录下

在这里插入图片描述

  • 使用hadoop命令
  • 上传
    在这里插入图片描述
  • 下载
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值