這篇文章主要介紹了使用hadoop的API對HDFS上的文件訪問,其中包括上傳文件到HDFS上、從HDFS上下載文件和刪除HDFS上的文件,須要的朋友能夠參考下
hdfs文件操做操做示例,包括上傳文件到HDFS上、從HDFS上下載文件和刪除HDFS上的文件,你們參考使用吧java
複製代碼 代碼以下:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;apache
import java.io.File;
import java.io.IOException;
public class HadoopFile {
private Configuration conf =null;oop
public HadoopFile(){
conf =new Configuration();
conf.addResource(new Path("/hadoop/etc/hadoop/core-site.xml"));
}this
public HadoopFile(Configuration conf){
this.conf =conf;
}.net
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);xml
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();htm
FileStatus[] hadfiles= hadoopFS.listStatus(hadPath);
for(FileStatus fs :hadfiles){
System.out.println(fs.toString());
}
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}hadoop
public boolean delFile(String hadfile){
try {get
FileSystem hadoopFS =FileSystem.get(conf);
Path hadPath=new Path(hadfile);
Path p=hadPath.getParent();
boolean rtnval= hadoopFS.delete(hadPath, true);it
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;
}
}
詳細出處參考:http://www.jb51.net/article/48104.htm