Java文字列の圧縮と解凍の2つの方法
アプリケーションシーン
文字列が長すぎると、
文字列の値をデータベースに保存したい場合、フィールドの長さが足りないと挿入に失敗します。
あるいはHttp転送が必要な場合は、パラメータ長が長すぎてhttp転送が失敗するなどです。
文字列圧縮と解凍方法
方法1:Java 8のgzipを使う
ウェブプロジェクトでは、サーバー側が暗号化された文字列をフロントエンドに戻し、フロントエンドがajaxを介して暗号化された文字列をサーバ側に送信するように要求した場合、http伝送中に暗号化された文字列の内容が変更され、サーバが圧縮文字列を伸張することに異常が発生します。
java.util.zip.Zip Exception:Not in GZIP format
解決方法:
文字列を圧縮した後、圧縮された文字列BASE 64を暗号化し、使用時にBASE 64を復号してから解凍すれば良い。
この記事ではJava文字列の圧縮と解凍に関する2つの方法について紹介します。Java文字列の圧縮内容については、以前の文章を検索したり、下記の関連記事を見たりしてください。これからもよろしくお願いします。
文字列が長すぎると、
文字列の値をデータベースに保存したい場合、フィールドの長さが足りないと挿入に失敗します。
あるいはHttp転送が必要な場合は、パラメータ長が長すぎてhttp転送が失敗するなどです。
文字列圧縮と解凍方法
方法1:Java 8のgzipを使う
/**
* gzip
* @param str
* @return
*/
public static String compress(String str) {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = null;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzip != null) {
try {
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new sun.misc.BASE64Encoder().encode(out.toByteArray());
}
/**
* gzip
* @param compressedStr
* @return
*/
public static String uncompress(String compressedStr) {
if (compressedStr == null) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = null;
GZIPInputStream ginzip = null;
byte[] compressed = null;
String decompressed = null;
try {
compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
in = new ByteArrayInputStream(compressed);
ginzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = ginzip.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
decompressed = out.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ginzip != null) {
try {
ginzip.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return decompressed;
}
方法二:org.apache.com mmons.co.dec.binary.Base 64を使う。
/**
* org.apache.commons.codec.binary.Base64
* @param str
* @return
*/
public static String compress(String str) {
if (str == null || str.length() == 0) {
return str;
}
return Base64.encodeBase64String(str.getBytes());
}
/**
* org.apache.commons.codec.binary.Base64
* @param compressedStr
* @return
*/
public static String uncompress(String compressedStr) {
if (compressedStr == null) {
return null;
}
return Base64.decodeBase64(compressedStr);
}
注意事項ウェブプロジェクトでは、サーバー側が暗号化された文字列をフロントエンドに戻し、フロントエンドがajaxを介して暗号化された文字列をサーバ側に送信するように要求した場合、http伝送中に暗号化された文字列の内容が変更され、サーバが圧縮文字列を伸張することに異常が発生します。
java.util.zip.Zip Exception:Not in GZIP format
解決方法:
文字列を圧縮した後、圧縮された文字列BASE 64を暗号化し、使用時にBASE 64を復号してから解凍すれば良い。
この記事ではJava文字列の圧縮と解凍に関する2つの方法について紹介します。Java文字列の圧縮内容については、以前の文章を検索したり、下記の関連記事を見たりしてください。これからもよろしくお願いします。