Skip to content

Instantly share code, notes, and snippets.

@seraphy
Created July 4, 2012 16:44
Show Gist options
  • Save seraphy/3048259 to your computer and use it in GitHub Desktop.
Save seraphy/3048259 to your computer and use it in GitHub Desktop.
Deflate/Inflateの使い方サンプル
package deflatesample;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* Deflate/Inflateの使い方サンプル
*
* @author seraphy
*/
public class DeflateSample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// 圧縮されたバイト列を扱うチャンクサイズ
final int COMPRESSED_CHUNK_SIZE = 512;
// 圧縮されていないバイト列を扱うチャンクサイズ
final int ORIGINAL_CHUNK_SIZE = 512;
/// 圧縮処理
byte[] compressedData;
{
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
Deflater compresser = new Deflater();
try {
byte[] outBuf = new byte[COMPRESSED_CHUNK_SIZE];
Iterator<String> ite = generateData(10000); //テストデータ生成
while (ite.hasNext()) {
String token = ite.next();
byte[] data = token.getBytes("UTF-8");
compresser.setInput(data);
if (!ite.hasNext()) {
compresser.finish();
}
for (;;) {
int siz = compresser.deflate(outBuf);
if (siz > 0) {
bos.write(outBuf, 0, siz);
} else {
break;
}
}
}
} finally {
compresser.end();
}
compressedData = bos.toByteArray();
}
}
/// 伸張処理
{
final Inflater decompresser = new Inflater();
try {
try (InputStream bis = new ByteArrayInputStream(compressedData)) {
final byte[] inpBuf = new byte[COMPRESSED_CHUNK_SIZE];
final byte[] outBuf = new byte[ORIGINAL_CHUNK_SIZE];
int rd;
do {
rd = bis.read(inpBuf);
if (rd > 0) {
decompresser.setInput(inpBuf, 0, rd);
}
while (!decompresser.finished()) {
int siz = decompresser.inflate(outBuf);
if (siz > 0) {
// 実質上、ASCII文字のみと想定している.
// (マルチバイト文字列の分割位置を考慮していない)
String out = new String(outBuf, 0, siz, "UTF-8");
System.out.println("*" + out);
} else {
break;
}
}
} while (rd > 0);
}
} finally {
decompresser.end();
}
}
}
/**
* 引数で指定された個数までの連続した文字列データを生成するイテレータを返す.
*
* @param mx 最大個数
* @return 文字データを返すイテレータ
*/
public static Iterator<String> generateData(final int mx) {
return new Iterator<String>() {
private int idx = 0;
private boolean mode = false;
@Override
public boolean hasNext() {
return idx < mx;
}
@Override
public String next() {
mode = !mode;
if (mode) {
return "(" + Integer.toString(idx++) + ")";
} else {
return " ";
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment