java操作HDFS

package com.imooc.hdfs;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
/**
 * Java代码操作HDFS
 * 文件操作:上传文件、下载文件、删除文件
 * Created by xuwei
 */
public class HdfsOp {
    public static void main(String[] args) throws Exception{
        //创建一个配置对象
        Configuration conf = new Configuration();
        //指定HDFS的地址
        conf.set("fs.defaultFS","hdfs://bigdata01:9000");
        //获取操作HDFS的对象
        FileSystem fileSystem = FileSystem.get(conf);
        put(fileSystem);
        get(fileSystem);
        delete(fileSystem);
        FileStatus[] fileStatuses=fileSystem.listStatus(new Path("/d1/"));
        for (FileStatus fs:fileStatuses){
            System.out.println();
            System.out.println(fs.getPath()+":");
            BlockLocation[] blocks= fileSystem.getFileBlockLocations(fs,0,fs.getLen());
            for (BlockLocation block:blocks){
                System.out.println(block);
            }
            System.out.println();
        }
    }
    /**
     * 删除文件
     * @param fileSystem
     * @throws IOException
     */

    private static void delete(FileSystem fileSystem) throws IOException {
        //删除文件,目录也可以删除
        //如果要递归删除目录,则第二个参数需要设置为true
        // 如果是删除文件或者空目录,第二个参数会被忽略
        boolean flag= fileSystem.delete(new Path("/LICENSE.txt"),true);
        if (flag){
            System.out.println("删除成功! ");
        }
        else {
            System.out.println("删除失败! ");
        }
    }
    /**
     * 下载文件
     * @param fileSystem
     * @throws IOException
     */
    private static void get(FileSystem fileSystem) throws IOException {
        // 获取HDFS文件系统的输入流
        FSDataInputStream fis= fileSystem.open(new Path("/README.txt"));
        // 获取本地文件的输出流
        FileOutputStream fos=new FileOutputStream("D:\\README.txt");
        // 下载文件
        IOUtils.copyBytes(fis,fos,1024,true);
    }
    /**
     * 文件上传
     * @param fileSystem
     * @throws IOException
     */
    private static void put(FileSystem fileSystem) throws IOException {
        //获取HDFS文件系统的输出流
        FSDataOutputStream fos = fileSystem.create(new Path("/user.txt"));
        //获取本地文件的输入流
        FileInputStream fis = new FileInputStream("D:\\user.txt");

        //上传文件:通过工具类把输入流拷贝到输出流里面,实现本地文件上传到HDFS
        IOUtils.copyBytes(fis,fos,1024,true);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金融小白数据分析之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值