hadoop的hdfs文件操作实现上传文件到hdfs
hdfs文件操作操作示例,包括上传文件到HDFS上、从HDFS上下载文件和删除HDFS上的文件,大家参考使用吧
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;
}
}
相关文章
SpringBoot中的static静态资源访问、参数配置、代码自定义访问规则详解
这篇文章主要介绍了SpringBoot的static静态资源访问、参数配置、代码自定义访问规则,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-07-07
Java中不得不知的Collection接口与Iterator迭代器
这篇文章主要介绍了Java中的Collection接口与Iterator迭代器,文中有详细的代码示例供大家参考,对我们的学习或工作有一定的帮助,需要的朋友可以参考下2023-06-06
SpringCloud使用Nacos保存和读取变量的配置方法
在使用SpringCloud开发微服务时,经常会遇到一些比较小的后台参数配置,这些配置不足以单独开一张表去存储,而且其他服务会读取该参数,这篇文章主要介绍了SpringCloud使用Nacos保存和读取变量,需要的朋友可以参考下2022-07-07


最新评论