hadoop-HDFS流式数据访问

HDFS的文件系统输入输出流:
FSDataInputStream
FSDataOutputStream
本地文件系统输入输出流:
FileOutputStream
FileIntputStream
如果是上传:
创建HDFS文件系统的输入流
创建本地文件的输出流
直接对接即可

in = new FSDataInputStream(new Path(""))
out = new FileOutputStream(new File(""))
IOUtils.copy(out,in,4096,true)

案例演示

/**
* 相对那些封装好的方法而言的更底层一些的操作方式 上层那些MapReduce、Spark等运算框架,去 HDFS中获取数据的时候,就是调的这种底层的API
 */
  public class StreamAccess {
    FileSystem fs = null;
    @Before
    public void init() throws Exception {
        Configuration conf = new Configuration();
        System.setProperty("HADOOP_USER_NAME", "bigdata");
        conf.set("fs.defaultFS", "hdfs://bigdata02:9000");
        fs = FileSystem.get(conf);
        
        // fs = FileSystem.get(new URI("hdfs://bigdata02:9000"), conf, "bigdata");
    }

    @Test
    public void testDownLoadFileToLocal() throws IllegalArgumentException,IOException {
        // 先获取一个文件的输入流----针对hdfs上的
        FSDataInputStream in = fs.open(new Path("/jdk.tar.gz"));
        // 再构造一个文件的输出流----针对本地的
        FileOutputStream out = new FileOutputStream(new File("c:/jdk.tar.gz"));
        // 再将输入流中数据传输到输出流
        IOUtils.copyBytes(in, out, 4096, true);
    }

    @Test
    public void testUploadByStream() throws Exception {
        // hdfs文件的输出流
        FSDataOutputStream fsout = fs.create(new Path("/aaa.txt"));
        // 本地文件的输入流
        FileInputStream fsin = new FileInputStream("c:/111.txt");

        IOUtils.copyBytes(fsin, fsout, 4096, true);
    }

    /**
     * hdfs支持随机定位进行文件读取,而且可以方便地读取指定长度 用于上层分布式运算框架并发处 理数据
     */
    @Test
    public void testRandomAccess() throws IllegalArgumentException, IOException {
        // 先获取一个文件的输入流----针对hdfs上的
        FSDataInputStream in = fs.open(new Path("/student.txt"));
        // 可以将流的起始偏移量进行自定义
        in.seek(22);
        // 再构造一个文件的输出流----针对本地的
        FileOutputStream out = new FileOutputStream(new 
File("d:/student2.txt"));
        IOUtils.copyBytes(in, out, 19L, true);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值