.NET中为我们提供了一些用于压缩和解压缩的类,其中GZipStream是比较常用的之一。通过GZipStream的构造函数我们知道,可以通过向GZipStream的构造函数传入CompressonMode参数指定生成的该实例是用于压缩(Compress)还是解压缩(Decompress)。
1 public GZipStream(Stream stream, CompressionMode mode);
该构造函数表明我们还需要指定一个流对象作为输入参数。注意这里的stream所对应的一定是一个和压缩有关的流。也就是说,如果我们指定CompressionMode为Decompress的话,那么stream对象应该为一个输入流(input stream),该输入流的格式已经压缩过的,我们通过GZipStream的实例将压缩数据(input stream)读取出来后生成的数据就为解压缩过后的数据了。如果我们指定CompressionMode为Compression的话,那么stream对应的流一定是一个将要压缩的输出流 (output stream),我们通过GZipStream的实例将普通流写入输出流中,输出流中的数据就为压缩后的数据了。
例1: 现在有一个已经压缩好的文件FileA.txt.gz,我们现在要做的工作是将该文件解压缩为FileB.txt。具体步骤通过下面的代码演示:
1 //input file (already compressed) 2 string fileA = "FileA.txt.gz"; 3 //output file (need to decompress FileA then write to fileB) 4 string fileB = "FileB.txt"; 5 6 //byte array buffer 7 byte[] buffer = new byte[BUFFER_SIZE]; 8 int bytesReaded = 0; 9 10 11 //input file stream 12 Stream fileAStream = new FileStream(fileA, FileMode.Open, FileAccess.Read); 13 //output file stream 14 Stream fileBStream = new FileStream(fileB, FileMode.Create, FileAccess.Write); 15 //use fileAStream as inputStream 16 GZipStream gzipStream = new GZipStream(fileAStream, CompressionMode.Decompress); 17 18 do 19 { 20 //read from inputStream, data in buffer is decopressed 21 bytesReaded = gzipStream.Read(buffer, 0, BUFFER_SIZE); 22 //writed decompressed data into output stream 23 fileBStream.Write(buffer, 0, bytesReaded); 24 } while (bytesReaded > 0); 25 26 //close related streams. 27 fileAStream.Close(); 28 gzipStream.Close(); 29 fileBStream.Close();
例2:现在我们已经将FileA.txt.gz文件解压缩为FileB.txt文件了。接下来的实例演示了如果将FileB.txt压缩为FileC.txt.gz
1 //input file (flat file) 2 string fileB = "FileB.txt"; 3 //output file (need to be compressed from FileB then write to FileC) 4 string fileC = "FileC.txt.gz"; 5 6 //byte array buffer 7 byte[] buffer = new byte[BUFFER_SIZE]; 8 int bytesReaded = 0; 9 10 //input stream 11 Stream fileBStream = new FileStream(fileB, FileMode.Open, FileAccess.Read); 12 //output stream 13 Stream fileCStream = new FileStream(fileC, FileMode.Create, FileAccess.Write); 14 //specify fileCStream as target stream, we need to compress fileB then write to fileC, so specify CompressionMode to Compress 15 GZipStream gzipStream = new GZipStream(fileCStream, CompressionMode.Compress); 16 17 do 18 { 19 //read from fileBStream 20 bytesReaded = fileBStream.Read(buffer, 0, BUFFER_SIZE); 21 //write to fileCStream 22 gzipStream.Write(buffer, 0, bytesReaded); 23 } while (bytesReaded > 0); 24 //close related streams. 25 fileBStream.Close(); 26 gzipStream.Close(); 27 fileCStream.Close();
时间: 2024-10-12 12:06:12