本地多级文件 原样上传到hdfs

本文介绍了一种将本地多级文件夹结构原样上传到HDFS的方法,通过递归方式实现了文件夹及其内容的完整迁移。

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

package com.hdfs;


import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;


import com.beicai.utils.MyUtils;
/**
 * 
 * @described 本地多级文件 原样上传到hdfs
 */
public class HdfsWork {


public static void main(String[] args) throws Exception {
myMerge();
System.out.println("ok");
}

public static void myWrite(Path path,LocalFileSystem lfs,FileSystem fs) throws Exception{
FileStatus[] fst = lfs.listStatus(path);
for(int i=0;i<fst.length;i++){
Path dir = fst[i].getPath();//获取路径
//file:/D:/data/a
dir = new Path(dir.toString().split(":")[2]);//截取相对本地磁盘D盘的绝对路径

if(fst[i].isDirectory()){//是文件夹

myWrite(fst[i].getPath(),lfs,fs);//调用本身
fs.mkdirs(dir);//创建里面没有文件的文件夹(空文件夹)
} else {
FSDataInputStream fsdis = lfs.open(fst[i].getPath()); //打开文件输入流
FSDataOutputStream fsdos = fs.create(dir);//打开文件输出流流

int read = 0;
byte[] buffer = new byte[255];
while((read=fsdis.read(buffer))>0){
fsdos.write(buffer, 0, read);
}

IOUtils.closeStream(fsdis);//关闭流
IOUtils.closeStream(fsdos);
}
}
}

public static void myMerge() throws Exception{
FileSystem fs = MyUtils.getFileSystem();
LocalFileSystem lfs = MyUtils.getLocalFileSystem();
Path localPath = new Path("D:/datas");//本地路径


myWrite(localPath,lfs,fs);//调用方法
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值