1. 程式人生 > >Snappy文字壓縮(備忘)

Snappy文字壓縮(備忘)

直接上程式碼,感覺還是挺高效的。

package com.fenbi.commons.spider.services.utils;

import com.fenbi.commons.core.log.GLog;
import org.xerial.snappy.Snappy;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author chaiqx
 * 壓縮文字
 */
public class CompressUtils {

    /**
     * 壓縮文字
     *
     * @param text
     * @return
     */
    public static byte[] compressText(String text) {
        byte[] tempBytes = text.getBytes(StandardCharsets.UTF_8);
        //GLog.info("壓縮前:" + tempBytes.length);
        try {
            byte[] compressedText = Snappy.compress(tempBytes);
            //GLog.info("壓縮後:" + compressedText.length);
            return compressedText;
        } catch (IOException e) {
            GLog.error("compress text error, ", e);
        }
        return null;
    }

    /**
     * 解壓文字
     *
     * @param bytes
     * @return
     */
    public static String deCompressText(byte[] bytes) {
        try {
            return Snappy.uncompressString(bytes);
        } catch (IOException e) {
            GLog.error("uncompress text error, ", e);
        }
        return null;
    }

}