본문 바로가기

Computer Science/Spring

[Spring] LZ4 압축 및 압축 해제 (FILE)

LZ4 압축 및 압축해제 in JAVA

 

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.codec.binary.Base64;

import net.jpountz.lz4.LZ4FrameInputStream;
import net.jpountz.lz4.LZ4FrameOutputStream;

public class Lz4Compress {

	public static final int DEFAULT_BUFFER_SIZE = 8192;
	public static final int EOF = -1;

	public static byte[] compress(final byte[] bytes) throws IOException {

		try (ByteArrayOutputStream rstBao = new ByteArrayOutputStream();) {

			try (LZ4FrameOutputStream zos = new LZ4FrameOutputStream(rstBao);) {
				zos.write(bytes);
			}

			byte[] bts = rstBao.toByteArray();

			return Base64.encodeBase64(bts);
		}
	}

	public static byte[] uncompress(byte[] bytes) throws IOException {
		byte[] result = null;

		try (final InputStream input = new LZ4FrameInputStream(new ByteArrayInputStream(Base64.decodeBase64(bytes)));) {

			try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) {
				byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
				if (input != null) {
					while (EOF != (input.read(buffer))) {
						output.write(buffer);
					}
				}
				result = output.toByteArray();
			}
		}

		return result;
	}

}
반응형