import java.io.FileInputStream;java
import java.io.FileOutputStream;算法
import org.apache.hadoop.conf.Configuration;apache
import org.apache.hadoop.io.IOUtils;ide
import org.apache.hadoop.io.compress.CompressionOutputStream;oop
import org.apache.hadoop.io.compress.DeflateCodec;編碼
import org.apache.hadoop.util.ReflectionUtils;spa
import org.junit.BeforeClass;code
import org.junit.Test;對象
public class TestCompressDemo {hadoop
private static Configuration conf;
@BeforeClass
public static void iniConf(){
conf = new Configuration();
}
/**
* 使用deflate壓縮算法
*/
@Test
public void compressByDeflate() throws Exception{
//deflate編碼器
String codecStr = "org.apache.hadoop.io.compress.DeflateCodec";
Class<DeflateCodec> clazz = (Class<DeflateCodec>) Class.forName(codecStr);
DeflateCodec codec = ReflectionUtils.newInstance(clazz,conf);
//對輸出流包裝,產生新的壓縮流
FileOutputStream fos = new FileOutputStream("E:/zhaopian.deflate");
CompressionOutputStream comOut = codec.createOutputStream(fos);
//寫入流
IOUtils.copyBytes(new FileInputStream("E:/zhaopian.jpg"),comOut,1024);
}
/**
* 使用deflate壓縮算法
*/
@Test
public void compressByDeflate2() throws Exception{
//直接實例化codec對象
DeflateCodec codec = new DeflateCodec();
//檢查並設置conf對象
ReflectionUtils.setConf(codec,conf);
//對輸出流包裝,產生新的壓縮流
FileOutputStream fos = new FileOutputStream("E:/zhaopian2.deflate");
CompressionOutputStream comOut = codec.createOutputStream(fos);
//寫入流
IOUtils.copyBytes(new FileInputStream("E:/zhaopian.jpg"), comOut, 1024);
}
}