package demo02.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import org.apache.commons.codec.CharEncoding;
import org.xerial.snappy.Snappy;
/**
* 使用snappy壓縮算法壓縮文件
* @author gujie
*
*/
public class SnappyUtil {
public static void main(String[] args) throws IOException {
long time1 = new Date().getTime();
//輸入文件
File fileread = new File("D:\\Users\\gujie\\Desktop\\js\\46818_19279_4547_50.json");
//壓縮後文件
File fileWrite = new File("D:\\Users\\gujie\\Desktop\\js\\snappytest.snappy");
String charEncoding = CharEncoding.ISO_8859_1;//只能是ISO_8859_1,由byte[]的編碼決定
//讀取文件
String readFile = readFile(fileread, charEncoding);
System.out.println("read during(" + (new Date().getTime() - time1) + ")");
//壓縮內容
long time2 = new Date().getTime();
byte[] compressHtml = compressHtml(readFile);
System.out.println("snappy during(" + (new Date().getTime() - time2) + ")");
//存儲壓縮內容
time2 = new Date().getTime();
writeFile(fileWrite, compressHtml, charEncoding);
System.out.println("snappy save during(" + (new Date().getTime() - time2) + ")");
//讀取壓縮文件
long time3 = new Date().getTime();
String snappyStr = readFile(fileWrite,charEncoding);
System.out.println("read snappy during(" + (new Date().getTime() - time3) + ")");
//解壓壓縮文件內容
long time4 = new Date().getTime();
String decompressHtml = decompressHtml(snappyStr.getBytes(charEncoding));
// System.out.println("dec file:"+decompressHtml);
System.out.println("decode snappy during(" + (new Date().getTime() - time4) + ")");
//查看壓縮比
long totalSpaceBefore = fileread.length();
long totalSpaceAfter = fileWrite.length();
System.out.println("壓縮前:" + totalSpaceBefore + "\t壓縮後:" + totalSpaceAfter + "\t壓縮比:"
+ totalSpaceAfter * 1.0 / totalSpaceBefore);
}
/**
* 寫文件接口
* @param file
* @param bytes
* @param encodeing
* @throws IOException
*/
public static void writeFile(File file, byte[] bytes, String encodeing) throws IOException {
OutputStreamWriter op = new OutputStreamWriter(new FileOutputStream(file), encodeing);
op.append(new String(bytes,encodeing));
op.flush();
op.close();
}
/**
* 讀文件接口
* @param file
* @param encodeing
* @return
*/
public static String readFile(File file, String encodeing) {
StringBuilder stringBuffer = new StringBuilder();
try {
byte [] fileBytes = Files.readAllBytes(Paths.get(file.getPath()));
return new String(fileBytes,encodeing);
} catch (IOException e) {
e.printStackTrace();
}
return stringBuffer.toString();
}
/**
* 壓縮字符串
* @param html
* @return
*/
public static byte[] compressHtml(String html) {
try {
return Snappy.compress(html.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 解壓字節數組
* @param bytes
* @return
*/
public static String decompressHtml(byte[] bytes) {
try {
return new String(Snappy.uncompress(bytes));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
html