Hadoop学习笔记———《读、写HDFS文件》

本文介绍了如何使用Java API进行HDFS文件的读取和写入操作,包括配置Hadoop环境、打开文件系统连接、读取文件内容及将文本内容写入到指定的HDFS路径等关键步骤。

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

读取HDFS上的文件

  /**
     * Created by MJ on 15/12/06.
     *
     * @use 读取HDFS上的指定文件的内容并返回
     *
     * @param filePath 待写入的HDFS文件路径
     * @return String 文件的内容
     * @exception Exception 异常返回null
     */
    public String readHdfsFile(String filePath) throws Exception {
      FileSystem fileSystem = null;
      BufferedReader bufferedReader = null;
      try {
        String result = "";
        Configuration conf = new Configuration();
        fileSystem = FileSystem.get(conf);
        FSDataInputStream fs = fileSystem.open(new Path(filePath));
        bufferedReader = new BufferedReader(new InputStreamReader(fs));
        String lineString;
        while (null != (lineString = bufferedReader.readLine())) {
          result += lineString;
        }
        return result;
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (null != bufferedReader) {
          bufferedReader.close();
        }
        if (null != fileSystem) {
          fileSystem.close();
        }
      }
      return null;
    }

写入HDFS文件

/**
     * Created by MJ on 15/12/06.
     *
     * @use 将text内容写入到HDFS上的指定文件
     *
     * @param filePath 待写入的HDFS文件路径
     * @param text 待写入的内容
     * @exception
     */
    public void writeHdfsFile(String filePath, String text) throws Exception {
      FileSystem fileSystem = null;
      BufferedWriter bufferedWriter = null;
      try {
        Configuration conf = new Configuration();
        fileSystem = FileSystem.get(conf);
        FSDataOutputStream fs = fileSystem.create(new Path(filePath));
        bufferedWriter = new BufferedWriter(new OutputStreamWriter(fs));
        bufferedWriter.write(text + "\n");
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (null != bufferedWriter) {
          bufferedWriter.flush();
          bufferedWriter.close();
        }
        if (null != fileSystem) {
          fileSystem.close();
        }
      }
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值