java 上传文件到hdfs_hadoop的hdfs文件操作实现上传文件到hdfs

该博客介绍了如何使用Java API进行Hadoop HDFS文件操作,包括从本地上传文件到HDFS,删除HDFS上的文件以及从HDFS下载文件到本地。通过配置`Configuration`对象,读取`core-site.xml`,然后利用`FileSystem`类的方法实现文件的上传、删除和下载。
摘要由CSDN通过智能技术生成

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.fs.*;

import java.io.File;

import java.io.IOException;

public class HadoopFile {

private Configuration conf =null;

public HadoopFile(){

conf =new Configuration();

conf.addResource(new Path("/hadoop/etc/hadoop/core-site.xml"));

}

public HadoopFile(Configuration conf){

this.conf =conf;

}

public boolean sendFile(String path,String localfile){

File file=new File(localfile);

if (!file.isFile()) {

System.out.println(file.getName());

return false;

}

try {

FileSystem localFS =FileSystem.getLocal(conf);

FileSystem hadoopFS =FileSystem.get(conf);

Path hadPath=new Path(path);

FSDataOutputStream fsOut=hadoopFS.create(new Path(path+"/"+file.getName()));

FSDataInputStream fsIn=localFS.open(new Path(localfile));

byte[] buf =new byte[1024];

int readbytes=0;

while ((readbytes=fsIn.read(buf))>0){

fsOut.write(buf,0,readbytes);

}

fsIn.close();

fsOut.close();

FileStatus[] hadfiles= hadoopFS.listStatus(hadPath);

for(FileStatus fs :hadfiles){

System.out.println(fs.toString());

}

return true;

} catch (IOException e) {

e.printStackTrace();

}

return false;

}

public boolean delFile(String hadfile){

try {

FileSystem hadoopFS =FileSystem.get(conf);

Path hadPath=new Path(hadfile);

Path p=hadPath.getParent();

boolean rtnval= hadoopFS.delete(hadPath, true);

FileStatus[] hadfiles= hadoopFS.listStatus(p);

for(FileStatus fs :hadfiles){

System.out.println(fs.toString());

}

return rtnval;

} catch (IOException e) {

e.printStackTrace();

}

return false;

}

public boolean downloadFile(String hadfile,String localPath){

try {

FileSystem localFS =FileSystem.getLocal(conf);

FileSystem hadoopFS =FileSystem.get(conf);

Path hadPath=new Path(hadfile);

FSDataOutputStream fsOut=localFS.create(new Path(localPath+"/"+hadPath.getName()));

FSDataInputStream fsIn=hadoopFS.open(hadPath);

byte[] buf =new byte[1024];

int readbytes=0;

while ((readbytes=fsIn.read(buf))>0){

fsOut.write(buf,0,readbytes);

}

fsIn.close();

fsOut.close();

return true;

} catch (IOException e) {

e.printStackTrace();

}

return false;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值