java 读取hdfs上的文件内容

import com.nature.component.process.vo.DebugDataResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
 
import java.io.*;
import java.net.URI;
import java.util.*;
 
/**
 * 操作hdfs文件的工具类
 */
 
public class HdfsUtils {
 
    private static Logger logger = LoggerUtil.getLogger();
 
    /**
     * 读取hdfs指定路径的内容
     */
    public static String gethdfsData(String hdfsPath){
        String result = "";
        if(com.nature.third.utils.StringUtils.isNotEmpty(hdfsPath)){
            Path path = new Path(hdfsPath);
            Configuration configuration = new Configuration();
            FSDataInputStream fsDataInputStream = null;
            FileSystem fileSystem = null;
            BufferedReader br = null;
            // 定义一个字符串用来存储文件内容
            try {
                fileSystem = path.getFileSystem(configuration);
                fsDataInputStream = fileSystem.open(path);
                br = new BufferedReader(new InputStreamReader(fsDataInputStream));
                String str2;
                while ((str2 = br.readLine()) != null) {
                    // 遍历抓取到的每一行并将其存储到result里面
                    result += str2 + "\n";
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(br!=null){
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(fsDataInputStream!=null){
                    try {
                        fsDataInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(fileSystem!=null){
                    try {
                        fileSystem.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            logger.debug("文件内容:" + result);
        }
        return result;
    }
 
}

核心方法:

Path path = new Path("hdfs://192.168.1.111:9000/test/1234log");
Configuration configuration = new Configuration();
FileSystem fileSystem = path.getFileSystem(configuration);
FSDataInputStream fsDataInputStream = fileSystem.open(path);

注意我加的那些编码格式,可以防止中文乱码!!
这种方式即可以读取hdfs上面的文件也可以读取本地文件

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值