データの圧縮と展開
Posted feedbacks - Java
Javaなので、標準のzip圧縮を。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class Sample224 {
public byte[] compress(InputStream stream) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
zos.putNextEntry(new ZipEntry(""));
try {
BufferedInputStream bis = new BufferedInputStream(stream);
try {
byte[] buffer = new byte[4096];
int len = 0;
while ( (len = bis.read(buffer)) != -1 ) {
zos.write(buffer, 0, len);
}
} finally {
if (bis != null) bis.close();
}
} finally {
if (zos != null) {
zos.closeEntry();
zos.close();
}
}
return baos.toByteArray();
}
public byte[] decompress(byte[] input) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(input));
try {
zis.getNextEntry();
byte[] buffer = new byte[4096];
int len = 0;
while ( (len = zis.read(buffer)) != -1 ) {
baos.write(buffer, 0, len);
}
} finally {
if (zis != null) zis.close();
}
return baos.toByteArray();
}
public static void main(String[] args) throws IOException {
ByteArrayInputStream stream = new ByteArrayInputStream((
"データを圧縮するcompress、展開するdecompressという関数やメソッドなどを書いてください。データはバイト列でもストリームでもそれ以外の形式でもOKです。\n" +
"圧縮形式は問いませんが、できるだけ一般的なフォーマット(zip,lzhなど)でお願いします。\n" +
"また、標準以外のライブラリを使う場合には出典の記載をお願いします。\n" +
"「○○でも実用的な圧縮/展開プログラムがかけるんだぞ!」というのを、ぜひ示してください。\n"
).getBytes());
Sample224 zip = new Sample224();
byte[] compressData = zip.compress(stream);
System.out.println("compress size=" + compressData.length);
byte[] decompressData = zip.decompress(compressData);
System.out.println("decompress size=" + decompressData.length);
System.out.println(new String(decompressData));
}
}
|
投稿の時、ログインし忘れました><




mattsan
#8262()
Rating1/5=0.20
データを圧縮するcompress、展開するdecompressという関数やメソッドなどを書いてください。データはバイト列でもストリームでもそれ以外の形式でもOKです。
圧縮形式は問いませんが、できるだけ一般的なフォーマット(zip,lzhなど)でお願いします。
また、標準以外のライブラリを使う場合には出典の記載をお願いします。
「○○でも実用的な圧縮/展開プログラムがかけるんだぞ!」というのを、ぜひ示してください。
[ reply ]