本文主要比较了Java和.NET提供的GZIP压缩功能。 介绍在本文中,我们将讨论Java和.NET提供的GZIP压缩功能,并且用实例来说明哪个压缩方法更佳。 在Java中,我们有提供GZIP压缩的GZIPOutputStream类,这个类在Java.util.zip包中。而在.NET中,我们有执行GZIP压缩的GZipStream类,这个类在System.IO.Compression命名空间下。 我这里所说的更好方法针对的是小尺寸文件,因为我已经检验过小文件的效果,比如说当我们想在发送之前压缩我们的信息文件。 代码解析1)Java GZIPOutputStream类 该GZIPOutputStream类为压缩数据在GZIP格式文件中创建了输入流。这个类有以下几种的构造函数: 1.创建具有默认大小的输出流: GZIPOutputStream(OutputStream out); 2.创建新的具有默认缓冲区大小和指定刷新模式的输出流: GZIPOutputStream(OutputStream out,boolean syncFlush); 3.创建新的具有指定缓冲区大小的输出流: GZIPOutputStream(OutputStream out,int size); 4.创建新的具有指定的缓冲区大小和刷新模式的输出流: GZIPOutputStream(OutputStream out,int size,boolean syncFlush); 我们需要编写以下代码来压缩文件: import java.io.*;import java.util.zip.*;class abc{ public static void main(String args[]) { String srcfile="D:/abhi.txt"; String dstfile="D:/abhi1.txt"; try{ FileInputStream fin= new FileInputStream(srcfile); GZIPOutputStream fout=new GZIPOutputStream(new FileOutputStream(dstfile)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fin.read(buffer)) != -1) //srcfile.getBytes() { fout.write(buffer, 0, bytesRead); } fin.close(); fout.close(); File file =new File(srcfile); System.out.println("Before Compression file Size : " + file.length()+" Bytes"); File file1 =new File(dstfile); System.out.println("After Compression file Size : " + file1.length()+" Bytes"); }catch(Exception ex) { System.out.println(ex); } }} 运行代码。输出如下,因为我提供的源文件只有481个字节大小,然后经过压缩后输出的文件大小为207个字节。 现在,我们用相同的输入文件来看看GZIP压缩后的效果。 2).NET GZipStream类 GZipStream压缩string或文件。它可以让你有效地保存数据,如压缩日志文件,消息文件。这个类存在于System.IO.Compression的命名空间。它创建GZIP文件,并将其写入磁盘。 GZipStream类提供以下构造函数: 1.通过使用指定字节流和压缩等级初始化GZipStream类的新实例: GZipStream(Stream, CompressionLevel) 2.通过使用指定流和压缩模式初始化GZipStream类的新实例: GZipStream(Stream, CompressionMode) 3.通过使用指定流和压缩等级初始化GZipStream类的新实例,并可选是否打开流: GZipStream(Stream, CompressionLevel, Boolean) 4.通过使用指定流和压缩模式初始化GZipStream类的新实例,并可选是否打开流: GZipStream(Stream, CompressionMode, Boolean) 我们需要编写以下代码来压缩文件: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.IO.Compression;namespace Compress{ class Program { static void Main(string[] args) { string srcfile = "D:\\abhi.txt"; string dstfile = "D:\\abhi2.txt"; byte[] b; using (FileStream f = new FileStream(srcfile, FileMode.Open)) { b = new byte[f.Length]; f.Read(b, 0, (int)f.Length); } using (FileStream fs = new FileStream(dstfile, FileMode.Create)) using (GZipStream gzip = new GZipStream(fs, CompressionMode.Compress, false)) { gzip.Write(b, 0, b.Length); } FileInfo f2 = new FileInfo(srcfile); System.Console.WriteLine("Size Of File Before Compression :"+f2.Length); FileInfo f1 = new FileInfo(dstfile); System.Console.WriteLine("Size Of File Before Compression :" + f1.Length); }} 运行代码。输出如下,由于我提供的是481字节大小的源文件,然后压缩后的输出文件大小为353个字节。 大家可以看到,源文件为481字节,压缩文件大小为:
压缩后的尺寸大小差距很明显。因此,我们可以得出结论,Java的GZIP压缩比.NET更好。 兴趣点我是在使用IKVM.NET研究Java和.NET之间的互操作性时发现的。我认为这很有意思,所以分享给大家。 译文链接:http://www.codeceo.com/article/java-net-gzip.html |