用流的方式操作HDFS文件 JAVA API

该博客介绍了如何使用JAVA API以流的方式操作HDFS文件,包括上传、下载、读取指定偏移量范围的数据以及将文件内容输出到控制台。示例代码展示了如何初始化HDFS连接,并通过FSDataInputStream和FSDataOutputStream实现文件的读写操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.bpf.hdfs;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;

import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Before;
import org.junit.Test;

/* 用流的方式来操作HDFS上的文件
 * 可以实现读取制定偏移量范围的数据
 * */

public class HdfsStreamAccess {
    FileSystem fs = null;
    Configuration conf = null;
    
    //初始化,建立与HDFS的连接
    @Before
    public void init() throws Exception {
        conf = new Configuration();
        fs = FileSystem.get(new URI("hdfs://Master:9000"), conf);
    }
    
    //流的方式上传文件
    @Test
    public void testUpload() throws IllegalArgumentException, IOException {
        FSDataOutputStream outputStream = fs.create(new Path("/bpf.txt"), true);
        FileInputStream inputStream = new FileInputStream("E:/QQPCmgr/Desktop/test.txt");
        IOUtils.copy(inputStream, outputStream);
    }
    
    //流的方式下载文件
    @Test
    public void tetsDownload() throws IllegalArgumentException, IOException {
        FSDataInputStream inputStream = fs.open(new Path("/bpf.txt"));
        FileOutputStream outputStream = new FileOutputStream("E:/QQPCmgr/Desktop/test1.txt");
        IOUtils.copy(inputStream, outputStream);
    }
    
    //流的方式读取制定偏移量范围的数据
    @Test
    public void testRandomAccess() throws IllegalArgumentException, IOException {
        FSDataInputStream inputStream = fs.open(new Path("/bpf.txt"));
        //从第十三个字节开始读
        inputStream.seek(12);
        FileOutputStream outputStream = new FileOutputStream("E:/QQPCmgr/Desktop/test2.txt");
        IOUtils.copy(inputStream, outputStream);
    }
    
    //流的方式读取并输出文件内容到控制台
    @Test
    public void testCat() throws IllegalArgumentException, IOException {
        
        FSDataInputStream inputStream = fs.open(new Path("/bpf.txt"));
        IOUtils.copy(inputStream, System.out);
        
        
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值