分享

Java实现远程HDFS的文件操作(新建、上传、下载、删除)

 陈永正的图书馆 2017-02-22
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;


public class HDFSTest01 {

/**
* @author dcx by 2015.11.19
* 新建文件 
* @param dsta
* @param conf
* @return
*/
public static boolean CreatDir(String dst , Configuration conf){
Path dstPath = new Path(dst) ;
try{
FileSystem dhfs = FileSystem.get(conf);
       dhfs.mkdirs(dstPath);
}
catch(IOException ie){
ie.printStackTrace() ;
return false ;
}
return true ;
}
 

/**
* @author dcx by 2015.11.19
* 文件上传
* @param src 
* @param dst
* @param conf
* @return
*/
public static boolean putToHDFS(String src , String dst , Configuration conf){
Path dstPath = new Path(dst) ;
try{
FileSystem hdfs = dstPath.getFileSystem(conf) ;
hdfs.copyFromLocalFile(false, new Path(src), dstPath) ;
}
catch(IOException ie){
ie.printStackTrace() ;
return false ;
}
return true ;
}

/**
*  @author dcx by 2015.11.19
* 文件下载
* @param src
* @param dst
* @param conf
* @return
*/
public static boolean getFromHDFS(String src , String dst , Configuration conf){
Path dstPath = new Path(dst) ;
try{
FileSystem dhfs = dstPath.getFileSystem(conf) ;
dhfs.copyToLocalFile(false, new Path(src), dstPath) ;
}catch(IOException ie){
ie.printStackTrace() ;
return false ;
}
return true ;
}

 
/**
* @author dcx by 2015.11.19
* 文件删除
* @param path
* @param conf
* @return
*/
public static boolean checkAndDel(final String path , Configuration conf){
Path dstPath = new Path(path) ;
try{
FileSystem dhfs = dstPath.getFileSystem(conf) ;
if(dhfs.exists(dstPath)){
dhfs.delete(dstPath, true) ;
}else{
return false ;
}
}catch(IOException ie ){
ie.printStackTrace() ;
return false ;
}
return true ;
}




/**
* @param 主函数测试
*/
public static void main(String[] args) {

boolean status = false ;
String dst1 = "hdfs://192.168.1.225:9000/EBLearn_data/new" ;
Configuration conf = new Configuration() ;
 
//java.lang.IllegalArgumentException: Wrong FS:            hdfs://192.168.1.225:9000/EBLearn_data/hello.txt, expected: file:///
    //解决这个错误的两个方案:
//方案1:下面这条命令必须加上,否则出现上面这个错误
conf.set("fs.default.name", "hdfs://192.168.1.225:9000"); // "hdfs://master:9000"  
    //方案2: 将core-site.xml 和hdfs-site.xml放入当前工程中
   status = CreatDir( dst1 ,  conf) ;
   System.out.println("status="+status) ;

   String dst = "hdfs://192.168.1.225:9000/EBLearn_data" ;
String src = "I:/hello.txt" ;

   status = putToHDFS( src ,  dst ,  conf) ;
System.out.println("status="+status) ;
    
src = "hdfs://192.168.1.225:9000/EBLearn_data/hello.txt" ;
dst = "I:/hadoop_need/" ;
status = getFromHDFS( src ,  dst ,  conf) ;
System.out.println("status="+status) ;
 
dst = "hdfs://192.168.1.225:9000/EBLearn_data/hello.txt" ;
status = checkAndDel( dst ,  conf) ;
System.out.println("status="+status) ;
}




}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多