从HDFS复制一个文件夹到HDFS

本文提供了一个使用Java实现的HDFS文件操作示例,包括文件的复制和目录的复制功能。通过具体的方法实现了HDFS上的文件读写,并展示了如何进行目录的递归复制。
public class FileHandle {
    /**
     * 设置hadoop HDFS 初始化配置方法
     * @throws IOException 
     */
    public static FileSystem init(){
        Configuration config=new Configuration();
        config.set("fs.defaultFS", "hdfs://192.168.100.200:9000/");
        FileSystem fs=null;
        try{
            fs=FileSystem.get(config);
        }catch(Exception e){
            throw new RuntimeException("初始化异常");
        }   
        return fs;
    }



    /**
     * 将HDFS上文件复制到HDFS上
     * @param src   原目标
     * @param dsc   复制到的目标
     * @throws Exception 
     * @throws IllegalArgumentException 
     */
    public static void copy(String src,String dsc) throws IllegalArgumentException, Exception{
        /**
         * 1:建立输入流
         * 2:建立输出流
         * 3:两个流的对接
         * 4:资源的关闭
         */
        FileSystem fs=init();

        //1:建立输入流
        FSDataInputStream input=fs.open(new Path(src));

        //2:建立输出流
        FSDataOutputStream output=fs.create(new Path(dsc));

        //3:两个流的对接
        byte[] b= new byte[1024];
        int hasRead=0;
        while((hasRead=input.read(b))>0){
            output.write(b, 0, hasRead);
        }
        //4:资源的关闭
        input.close();
        output.close();
        fs.close();

    }
    /**
     * 复制一个目录下面的所有文件
     * @param src   需要复制的文件夹或文件
     * @param dsc   目的地
     * @throws Exception 
     * @throws FileNotFoundException 
     */
    public static void copyDir(String src,String dsc) throws FileNotFoundException, Exception{
        FileSystem fs=init();
        Path srcPath=new Path(src);
        String[] strs=src.split("/");
        String lastName=strs[strs.length-1];
        if(fs.isDirectory(srcPath)){    
            fs.mkdirs(new Path(dsc+"/"+lastName));

            //遍历
            FileStatus[] fileStatus=fs.listStatus(srcPath);
            for(FileStatus fileSta:fileStatus){
                copyDir(fileSta.getPath().toString(),dsc+"/"+lastName);
            }

        }else{
            fs.mkdirs(new Path(dsc));
            System.out.println("src"+src+"\n"+dsc+"/"+lastName);
            copy(src,dsc+"/"+lastName);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值