Created
October 26, 2012 09:41
-
-
Save monzou/3957873 to your computer and use it in GitHub Desktop.
SimpleCompressor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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