我在hdfs的资料夹中有一堆.gz文件。我想将所有这些.gz文件解压缩到hdfs中的新文件夹中。我应该怎么做?
最佳答案
我可以考虑通过3种不同的方式来实现它。
以下命令对我有用。
hadoop fs -cat /tmp/Links.txt.gz | gzip -d | hadoop fs -put - /tmp/unzipped/Links.txt
我的压缩文件是
Links.txt.gz
输出存储在/tmp/unzipped/Links.txt
在
Hadoop The Definitve Guide
书中,有一个关于Codecs
的部分。在该部分中,有一个程序使用CompressionCodecFactory
解压缩输出。我正在按原样重现该代码:package com.myorg.hadooptests;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
public class FileDecompressor {
public static void main(String[] args) throws Exception {
String uri = args[0];
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
Path inputPath = new Path(uri);
CompressionCodecFactory factory = new CompressionCodecFactory(conf);
CompressionCodec codec = factory.getCodec(inputPath);
if (codec == null) {
System.err.println("No codec found for " + uri);
System.exit(1);
}
String outputUri =
CompressionCodecFactory.removeSuffix(uri, codec.getDefaultExtension());
InputStream in = null;
OutputStream out = null;
try {
in = codec.createInputStream(fs.open(inputPath));
out = fs.create(new Path(outputUri));
IOUtils.copyBytes(in, out, conf);
} finally {
IOUtils.closeStream(in);
IOUtils.closeStream(out);
}
}
}
此代码将gz文件路径作为输入。
您可以这样执行:
FileDecompressor <gzipped file name>
例如当我执行压缩文件时:
FileDecompressor /tmp/Links.txt.gz
我在以下位置找到了解压缩的文件:
/tmp/Links.txt
它将解压缩的文件存储在同一文件夹中。因此,您需要修改此代码以采用2个输入参数:
<input file path> and <output folder>
。一旦该程序开始运行,您就可以编写一个Shell / Perl / Python脚本来为您的每个输入调用该程序。
您可以编写一个简单的Pig脚本来实现此目的。
我编写了以下脚本,该脚本有效:
A = LOAD '/tmp/Links.txt.gz' USING PigStorage();
Store A into '/tmp/tmp_unzipped/' USING PigStorage();
mv /tmp/tmp_unzipped/part-m-00000 /tmp/unzipped/Links.txt
rm /tmp/tmp_unzipped/
运行此脚本时,解压缩的内容存储在一个临时文件夹
/tmp/tmp_unzipped
中。此文件夹将包含/tmp/tmp_unzipped/_SUCCESS
/tmp/tmp_unzipped/part-m-00000
part-m-00000
包含解压缩的文件。因此,我们需要使用以下命令显式重命名它,最后删除
/tmp/tmp_unzipped
文件夹:mv /tmp/tmp_unzipped/part-m-00000 /tmp/unzipped/Links.txt
rm /tmp/tmp_unzipped/
因此,如果使用此Pig脚本,则只需注意参数化文件名(Links.txt.gz和Links.txt)。
同样,一旦使该脚本正常工作,您就可以编写一个Shell / Perl / Python脚本来为您的每个输入调用此Pig脚本。