read and write compressed files

July 26th, 2007
Sometimes you may want to read or write compressed files from your Java or .NET programs. This is fairly easy to accomplish in both platforms.

In Java you can use the GZIPInputStream and GZIPOutputStream to respectively read from and write to files or streams compressed in the GZIP format. These classes are part of the J2SE since version 1.4.2. Here is an example of reading a gzip-compressed file:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;

public class GZIPExample
{
public static void main( String[] args )
throws IOException
{
FileInputStream fileInputStream =
new FileInputStream("myCompressedFile.gz");
GZIPInputStream gzipInputStream =
new GZIPInputStream(fileInputStream);
InputStreamReader inputStreamReader =
new InputStreamReader(gzipInputStream);
BufferedReader in =
new BufferedReader(inputStreamReader);
String line;
while ((line = in.readLine()) != null)
System.out.println(line);
in.close();
}
}


Alternatively you can use ZIPInputStream and ZIPOutputStram to cope with file compressed in the ZIP format.

On the .NET platform you will need to get some third party libraries. #ZipLib (pronounced: Sharp-Zip-Lib) is a free open source library, written entirely in pure C# by ic#code. It supports the GZip, Zip, BZip2 and Tar formats. Here is an example that utilizes #ZipLib, it looks very much like the Java example above:

using System;
using System.IO;
using ICSharpCode.SharpZipLib.GZip;

namespace SharpZipLibTest
{
class Program
{
static void Main(string[] args)
{
FileStream fileStream =
File.OpenRead("myCompressedFile.gz");
GZipInputStream gzipInputStream =
new GZipInputStream(fileStream);
StreamReader input =
new StreamReader(gzipInputStream);
String line;
while ((line = input.ReadLine()) != null)
Console.WriteLine(line);
input.Close();
}
}
}


Leave a Reply