简单的hadoop数据压缩案例实操
编码思路
压缩
1.获取文件输入流
2.需要先获取一个普通的文件输出流,然后创建压缩文件的输出流,并将普通文件的输出流传入压缩文件输出流方法中,来做到输出压缩文件的效果(注意,还需要指定压缩的类型)
3.进行流的对拷
4.关闭流
解压缩
1.获取一个普通的文件输入流,再创建一个压缩文件的输入流,把普通文件输入流作为参数传入
2.对比上述压缩过程,需要加一个输入的文件是否是支持的压缩文件的判断
3.获取普通文件输出流
4.流的对拷
5.关闭流
代码实现
public class Compress {
public static void main(String[] args) throws IOException {
compress("这里写文件地址,精确到具体文件", "org.apache.hadoop.io.compress.BZip2Codec【压缩类型的全类名】");
decompress("这里写文件地址,精确到具体文件");
}
private static void decompress(String path) throws IOException {
// 0. 判断传入的文件是否支持解压缩
//获取压缩编解码器
Configuration conf = new Configuration();
CompressionCodecFactory codecFactory = new CompressionCodecFactory(conf);
CompressionCodec codec = codecFactory.getCodec(new Path(path));
if(codec == null){
System.out.println("该文件格式不支持!");
return;
}
// 1. 获取压缩文件输入流
FileInputStream fis = new FileInputStream(new File(path));
CompressionInputStream cis = codec.createInputStream(fis);
// 2. 获取普通文件输出流
FileOutputStream fos = new FileOutputStream(new File(path + "decodec"));
// 3. 流的对拷
IOUtils.copyBytes(cis, fos, conf);
// 4. 关流
IOUtils.closeStream(fos);
IOUtils.closeStream(cis);
IOUtils.closeStream(fis);
}
private static void compress(String path, String method) throws IOException {
Configuration conf = new Configuration();
// 1. 获取普通文件输入流
FileInputStream fis = new FileInputStream(new File(path));
// 2. 获取压缩文件输出流
//获取压缩编解码器
CompressionCodecFactory codecFactory = new CompressionCodecFactory(conf);
CompressionCodec codec = codecFactory.getCodecByName(method);
//获取普通文件输出流
FileOutputStream fos = new FileOutputStream(new File(path + codec.getDefaultExtension()));
CompressionOutputStream cos = codec.createOutputStream(fos);
// 3. 流的对拷
IOUtils.copyBytes(fis, cos, conf);
// 4. 流的关闭
IOUtils.closeStream(cos);
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
}
}