复用代码系列:6种字符串解压缩工具类

1、字符串解压缩(gzip方式)代码如下:

package com.compress;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.io.IOUtils;

/**
 * gzip解压缩工具类
 * @author suncht
 *
 */
public abstract class GZIPUtils  {
    
    public static byte[] compress(String str, Charset encoding) {
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = null;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(encoding));
            gzip.close();
        } catch ( Exception e) {
            e.printStackTrace();
        } finally {
        	IOUtils.closeQuietly(gzip);
        }
        return out.toByteArray();
    }
    
    public static byte[] compress(String str) throws IOException {  
        return compress(str, StandardCharsets.UTF_8);  
    }
    
    public static byte[] uncompress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        GZIPInputStream ungzip = null;
        try {
            ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	IOUtils.closeQuietly(ungzip);
        	IOUtils.closeQuietly(in);
        	IOUtils.closeQuietly(out);
        }
        return out.toByteArray();
    }
    
    public static String uncompressToString(byte[] bytes, Charset encoding) {  
        if (bytes == null || bytes.length == 0) {  
            return null;  
        }  
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        ByteArrayInputStream in = new ByteArrayInputStream(bytes); 
        GZIPInputStream ungzip = null;
        try {
            ungzip = new GZIPInputStream(in);  
            byte[] buffer = new byte[256];  
            int n;  
            while ((n = ungzip.read(buffer)) >= 0) {  
                out.write(buffer, 0, n);  
            }  
            return out.toString(encoding.name());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	IOUtils.closeQuietly(ungzip);
        	IOUtils.closeQuietly(in);
        	IOUtils.closeQuietly(out);
        }
        return null;
    }
    
    public static String uncompressToString(byte[] bytes) {  
        return uncompressToString(bytes, StandardCharsets.UTF_8);  
    } 
    
    public static void main(String[] args) throws IOException {
        String s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        System.out.println("字符串长度:"+s.length());
        System.out.println("压缩后::"+compress(s).length);
        System.out.println("解压后:"+uncompress(compress(s)).length);
        System.out.println("解压字符串后::"+uncompressToString(compress(s)).length());
    }
}

2、字符串解压缩(snappy方式),代码如下:

package com.compress;

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

import org.xerial.snappy.Snappy;

/**
 * 字符串解压缩(Snappy)
 * @author suncht
 *
 */
public class SnappyUtils {
	public static byte[] compressHtml(String str) {
		try {
			return Snappy.compress(str.getBytes(StandardCharsets.UTF_8));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String decompressHtml(byte[] bytes) {
		try {
			return new String(Snappy.uncompress(bytes), StandardCharsets.UTF_8);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		String s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdfasdfaaaaaaaaa12121sdgfas";
		System.out.println("字符串长度:" + s.length());
		System.out.println("压缩后::" + compressHtml(s).length);
		System.out.println("解压后:" + decompressHtml(compressHtml(s)).length());

	}
}

需要Snappy依赖:

<dependency>
		    <groupId>org.xerial.snappy</groupId>
		    <artifactId>snappy-java</artifactId>
		    <version>1.1.7.1</version>
		</dependency>

3、字符串解压缩(lz4方式),代码如下:

package com.compress;

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

import net.jpountz.lz4.LZ4BlockInputStream;
import net.jpountz.lz4.LZ4BlockOutputStream;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;

public class Lz4Utils {
	public static byte[] compress(byte srcBytes[]) throws IOException {
        LZ4Factory factory = LZ4Factory.fastestInstance();
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
        LZ4Compressor compressor = factory.fastCompressor();
        LZ4BlockOutputStream compressedOutput = new LZ4BlockOutputStream(
                byteOutput, 2048, compressor);
        compressedOutput.write(srcBytes);
        compressedOutput.close();
        return byteOutput.toByteArray();
    }

    public static byte[] uncompress(byte[] bytes) throws IOException {
        LZ4Factory factory = LZ4Factory.fastestInstance();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        LZ4FastDecompressor decompresser = factory.fastDecompressor();
        LZ4BlockInputStream lzis = new LZ4BlockInputStream(
                new ByteArrayInputStream(bytes), decompresser);
        int count;
        byte[] buffer = new byte[2048];
        while ((count = lzis.read(buffer)) != -1) {
            baos.write(buffer, 0, count);
        }
        lzis.close();
        return baos.toByteArray();
    }
    
    public static String uncompressToString(byte[] data) throws IOException {
    	return new String(uncompress(data), StandardCharsets.UTF_8);
    }
	
	public static void main(String[] args) throws IOException {
		String s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdfasdfaaaaaaaaa12121sdgfas";
		System.out.println("字符串长度:" + s.length());
		byte[] data = compress(s.getBytes(StandardCharsets.UTF_8));
		System.out.println("压缩后::" + data.length);
		System.out.println("解压后:" + uncompress(data).length);
		System.out.println("解压后字符串:" + uncompressToString(data));
	}
}

需要LZ4的依赖:

<dependency>
		    <groupId>net.jpountz.lz4</groupId>
		    <artifactId>lz4</artifactId>
		    <version>1.3.0</version>
		</dependency>

4、字符串解压缩(Bzip2方式),代码如下:

package com.compress;

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

import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;

public class Bzip2Utils {
	public static byte[] compress(byte srcBytes[]) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BZip2CompressorOutputStream bcos = new BZip2CompressorOutputStream(out);
        bcos.write(srcBytes);
        bcos.close();
        return out.toByteArray();
    }

    public static byte[] uncompress(byte[] bytes) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        try {
            BZip2CompressorInputStream ungzip = new BZip2CompressorInputStream(
                    in);
            byte[] buffer = new byte[2048];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return out.toByteArray();
    }
    
    public static String uncompressToString(byte[] data) throws IOException {
    	return new String(uncompress(data), StandardCharsets.UTF_8);
    }
    
    public static void main(String[] args) throws IOException {
		String s = "AAAAAAAAAAAAAAAAAA";
		System.out.println("字符串长度:" + s.length());
		byte[] data = compress(s.getBytes(StandardCharsets.UTF_8));
		System.out.println("压缩后::" + data.length);
		System.out.println("解压后:" + uncompress(compress(s.getBytes(StandardCharsets.UTF_8))).length);
		System.out.println("解压后字符串:" + uncompressToString(data));
	}
}

需要commons-compress依赖:

<dependency>
		    <groupId>org.apache.commons</groupId>
		    <artifactId>commons-compress</artifactId>
		    <version>1.12</version>
		</dependency>

5、字符串解压缩(Deflater/Inflater方式),代码如下:

package com.compress;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterUtils {
	public static byte[] compress(byte input[]) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Deflater compressor = new Deflater(1);
        try {
            compressor.setInput(input);
            compressor.finish();
            final byte[] buf = new byte[2048];
            while (!compressor.finished()) {
                int count = compressor.deflate(buf);
                bos.write(buf, 0, count);
            }
        } finally {
            compressor.end();
        }
        return bos.toByteArray();
    }

      public static byte[] uncompress(byte[] input) throws DataFormatException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Inflater decompressor = new Inflater();
        try {
            decompressor.setInput(input);
            final byte[] buf = new byte[2048];
            while (!decompressor.finished()) {
                int count = decompressor.inflate(buf);
                bos.write(buf, 0, count);
            }
        } finally {
            decompressor.end();
        }
        return bos.toByteArray();
    }
      
      public static String uncompressToString(byte[] input) throws DataFormatException {
    	  return new String(uncompress(input), StandardCharsets.UTF_8);
      }
      
      public static void main(String[] args) throws DataFormatException {
  		String s = "AAAAAAAAAAAAAAAAAA";
  		System.out.println("字符串长度:" + s.length());
  		byte[] data = compress(s.getBytes(StandardCharsets.UTF_8));
  		System.out.println("压缩后::" + data.length);
  		System.out.println("解压后:" + uncompress(compress(s.getBytes(StandardCharsets.UTF_8))).length);
  		System.out.println("解压后字符串:" + uncompressToString(data));
  	}
}

5、字符串解压缩(LZO方式),代码如下:

package com.compress;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.anarres.lzo.LzoAlgorithm;
import org.anarres.lzo.LzoCompressor;
import org.anarres.lzo.LzoDecompressor;
import org.anarres.lzo.LzoInputStream;
import org.anarres.lzo.LzoLibrary;
import org.anarres.lzo.LzoOutputStream;

public class LzoUtils {

	public static byte[] compress(byte srcBytes[]) throws IOException {
        LzoCompressor compressor = LzoLibrary.getInstance().newCompressor(
                LzoAlgorithm.LZO1X, null);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        LzoOutputStream cs = new LzoOutputStream(os, compressor);
        cs.write(srcBytes);
        cs.close();

        return os.toByteArray();
    }

    public static byte[] uncompress(byte[] bytes) throws IOException {
        LzoDecompressor decompressor = LzoLibrary.getInstance()
                .newDecompressor(LzoAlgorithm.LZO1X, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        LzoInputStream us = new LzoInputStream(is, decompressor);
        int count;
        byte[] buffer = new byte[2048];
        while ((count = us.read(buffer)) != -1) {
            baos.write(buffer, 0, count);
        }
        return baos.toByteArray();
    }
    
    public static String uncompressToString(byte[] data) throws IOException {
    	return new String(uncompress(data), StandardCharsets.UTF_8);
    }
    
	public static void main(String[] args) throws IOException {
		String s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdfasdfaaaaaaaaa12121sdgfas";
		System.out.println("字符串长度:" + s.length());
		byte[] data = compress(s.getBytes(StandardCharsets.UTF_8));
		System.out.println("压缩后::" + data.length);
		System.out.println("解压后:" + uncompress(data).length);
	}
}
需要LZO依赖:
<dependency>
		    <groupId>org.anarres.lzo</groupId>
		    <artifactId>lzo-core</artifactId>
		    <version>1.0.5</version>
		</dependency>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值