Skip to content

Instantly share code, notes, and snippets.

@monzou
Created October 26, 2012 09:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monzou/3957873 to your computer and use it in GitHub Desktop.
Save monzou/3957873 to your computer and use it in GitHub Desktop.
SimpleCompressor
package sandbox;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import org.apache.commons.io.IOUtils;
/**
* SimpleCompressor
*
* @author monzou
*/
final class SimpleCompressor {
private SimpleCompressor() {
}
/**
* 圧縮
*
* @param bytes バイナリ
* @return 圧縮されたバイナリ
*/
static byte[] compress(byte[] bytes) {
Deflater deflater = new Deflater();
deflater.setInput(bytes);
deflater.finish();
byte[] buf = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream();
do {
int size = deflater.deflate(buf);
out.write(buf, 0, size);
} while (!deflater.finished());
deflater.end();
try {
return out.toByteArray();
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* 解凍
*
* @param bytes バイナリ
* @return 解凍されたバイナリ
* @throws IOException I/O 例外
*/
static byte[] decompress(byte[] bytes) throws IOException {
byte[] buf = new byte[1024];
Inflater inflater = new Inflater();
inflater.setInput(bytes);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
do {
int size;
size = inflater.inflate(buf);
out.write(buf, 0, size);
} while (!inflater.finished());
} catch (DataFormatException e) {
throw new IOException(e);
}
inflater.end();
try {
return out.toByteArray();
} finally {
IOUtils.closeQuietly(out);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment