자바 스트링 압축 - Java String compress/decompress
자바로 스트링을 압축하는 방법을 찾고 찾다가 결국 못 찾고 직접 만든다.
보통 String 을 압축하요 byte[] 로 되돌려주는 프로그램은 쉽게 찾을 수 있으나 String 을 압축하여 String 으로 되돌려주는 코드는 찾을 수가 없었다.
그래서 찾은 방법들을 조합하여 하나의 클래스로 만들었다.
import java.io.*;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
/**
* Created by kimjinsam on 2015. 12. 7..
*/
public class CompressStringUtil {
private static final String charsetName = "UTF-8";
/**
* String 객체를 압축하여 String 으로 리턴한다.
* @param string
* @return
*/
public synchronized static String compressString(String string) {
return byteToString(compress(string));
}
/**
* 압축된 스트링을 복귀시켜서 String 으로 리턴한다.
* @param compressed
* @return
*/
public synchronized static String decompressString(String compressed) {
return decompress(hexToByteArray(compressed));
}
private static String byteToString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
try {
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return sb.toString();
}
private static byte[] compress(String text) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
OutputStream out = new DeflaterOutputStream(baos);
out.write(text.getBytes(charsetName));
out.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return baos.toByteArray();
}
private static String decompress(byte[] bytes) {
InputStream in = new InflaterInputStream(new ByteArrayInputStream(bytes));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[8192];
int len;
while ((len = in.read(buffer)) > 0)
baos.write(buffer, 0, len);
return new String(baos.toByteArray(), charsetName);
} catch (IOException e) {
e.printStackTrace();
throw new AssertionError(e);
}
}
/**
* 16진 문자열을 byte 배열로 변환한다.
*/
private static byte[] hexToByteArray(String hex) {
if (hex == null || hex.length() % 2 != 0) {
return new byte[]{};
}
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < hex.length(); i += 2) {
byte value = (byte) Integer.parseInt(hex.substring(i, i + 2), 16);
bytes[(int) Math.floor(i / 2)] = value;
}
return bytes;
}
}
성능평가를 해보니 9,404 의 길이를 가지는 String을 3,808 길이를 가지는 스트링으로 변경할 수 있었다.
'자바(Java)' 카테고리의 다른 글
| Java Enum class 제대로 사용하기. (12) | 2016.11.25 |
|---|---|
| G1 가비지 콜렉터 이전과 다른 점 & 동작 방식 (12) | 2016.09.30 |
| Java | AES-256 암호화 오류 해결 방법. JDK8 파일 첨부. (57) | 2015.10.22 |
| 클린 코드: 애자일 소프트웨어 장인 정신 - 예제 (13) | 2014.04.04 |
| 이클립스에서 주석을 제외한 한글 찾는 정규식 (2) | 2014.02.14 |
댓글