标题: Java中的Deflate/Inflate
创建: 2020-08-11 15:05 更新: 链接: https://scz.617.cn/web/202008111505.txt
/ * javac -encoding GBK -g DeflateTest.java * java DeflateTest src dst 0 * java DeflateTest dst src 1 / import java.io.; import java.util.zip.;
public class DeflateTest { private static void PrivateCopy ( InputStream is, OutputStream os ) throws Exception { int b;
while ( ( b = is.read() ) != -1 )
{
os.write( b );
}
os.close();
is.close();
} /* end of PrivateCopy */
private static void DeflateFile ( String src, String dst ) throws Exception
{
FileInputStream fis = new FileInputStream( src );
FileOutputStream fos = new FileOutputStream( dst );
/*
* https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html
* https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/zip/Deflater.html
*
* https://docs.oracle.com/javase/8/docs/api/java/util/zip/DeflaterOutputStream.html
*/
DeflaterOutputStream dos = new DeflaterOutputStream
(
fos,
/*
* If the parameter nowrap is true then the ZLIB header and
* checksum fields will not be used.
*/
new Deflater( 9, false ),
1024 * 1024
);
PrivateCopy( fis, dos );
} /* end of DeflateFile */
private static void InflateFile ( String src, String dst ) throws Exception
{
FileInputStream fis = new FileInputStream( src );
/*
* https://docs.oracle.com/javase/8/docs/api/java/util/zip/Inflater.html
* https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/zip/Inflater.html
*
* https://docs.oracle.com/javase/8/docs/api/java/util/zip/InflaterInputStream.html
*/
InflaterInputStream iis = new InflaterInputStream
(
fis,
new Inflater( false ),
1024 * 1024
);
FileOutputStream fos = new FileOutputStream( dst );
PrivateCopy( iis, fos );
} /* end of InflateFile */
public static void main ( String[] argv ) throws Exception
{
String src = argv[0];
String dst = argv[1];
int mode = Integer.parseInt( argv[2] );
switch ( mode )
{
/*
* 压缩
*/
case 0 :
DeflateFile( src, dst );
break;
/*
* 解压
*/
case 1 :
InflateFile( src, dst );
break;
}
}
}
$ xxd -g 1 src 0000000: 73 63 7a 20 69 73 20 68 65 72 65 scz is here
压缩:
$ java DeflateTest src dst 0 $ echo -ne 'scz is here' | python2 -c 'import sys,zlib;sys.stdout.write(zlib.compress(sys.stdin.read(),9))' > dst $ cat src | python2 -c 'import sys,zlib;sys.stdout.write(zlib.compress(sys.stdin.read(),9))' > dst
$ xxd -g 1 dst 0000000: 78 da 2b 4e ae 52 c8 2c 56 c8 48 2d 4a 05 00 18 x.+N.R.,V.H-J... 0000010: 6d 04 11 m..
解压:
$ java DeflateTest dst src 1 $ cat dst | python2 -c 'import sys,zlib;sys.stdout.write(zlib.decompress(sys.stdin.read()))' > src $ openssl zlib -d < dst > src
$ printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" | cat - dst | gzip -dc > src
gzip: stdin: unexpected end of file
有个警告,但解压无误。