Hadoop copyMerge()方法合并小文件

本文介绍了使用Hadoop FileUtil的copyMerge()方法和Hadoop命令行工具getmerge,实现HDFS中小文件的有效合并,避免了小文件过多带来的性能瓶颈。

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

// Hadoop的FileUtil工具类中提供了copyMerge()方法,
// 它专门用来将一个HDFS目录下的所有文件合并成一个文件并输出,其源码如下
  public static boolean copyMerge(FileSystem srcFS, Path srcDir, 
                                  FileSystem dstFS, Path dstFile, 
                                  boolean deleteSource,
                                  Configuration conf, String addString) throws IOException {
    dstFile = checkDest(srcDir.getName(), dstFS, dstFile, false);
 
    if (!srcFS.getFileStatus(srcDir).isDirectory())
      return false;
   
    OutputStream out = dstFS.create(dstFile);
    
    try {
      FileStatus contents[] = srcFS.listStatus(srcDir);
      Arrays.sort(contents);
      for (int i = 0; i < contents.length; i++) {
        if (contents[i].isFile()) {
          InputStream in = srcFS.open(contents[i].getPath());
          try {
            IOUtils.copyBytes(in, out, conf, false);
            if (addString!=null)
              out.write(addString.getBytes("UTF-8"));
                
          } finally {
            in.close();
          } 
        }
      }
    } finally {
      out.close();
    }
    
    if (deleteSource) {
      return srcFS.delete(srcDir, true);
    } else {
      return true;
    }
  }

方式二 : 通过命令 Usage: hadoop fs [generic options] -getmerge [-nl] [-skip-empty-file]

将hdfs小文件合并到本地,然后删除hdfs原文件,再将本地文件上传到hdfs
hadoop fs -getmerge -skip-empty-file /hdfspath/* /localpath/test.txt
hdfs dfs -put /localpath/test.txt /hdfspath/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值