I want trying to use the Deflate and Inflate classes in java.util.zip for zlib compression.
I am able to compress the code using Deflate, but while decompressing, I
Paŭlo Ebermann's code can be further improved by using try-with-resources:
import java.util.Scanner;
import java.util.zip.*;
import java.io.*;
public class ZLibCompression
{
public static void compress(File raw, File compressed) throws IOException
{
try (InputStream inputStream = new FileInputStream(raw);
OutputStream outputStream = new DeflaterOutputStream(new FileOutputStream(compressed)))
{
copy(inputStream, outputStream);
}
}
public static void decompress(File compressed, File raw)
throws IOException
{
try (InputStream inputStream = new InflaterInputStream(new FileInputStream(compressed));
OutputStream outputStream = new FileOutputStream(raw))
{
copy(inputStream, outputStream);
}
}
public static String decompress(File compressed) throws IOException
{
try (InputStream inputStream = new InflaterInputStream(new FileInputStream(compressed)))
{
return toString(inputStream);
}
}
private static String toString(InputStream inputStream)
{
try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"))
{
return scanner.hasNext() ? scanner.next() : "";
}
}
private static void copy(InputStream inputStream, OutputStream outputStream)
throws IOException
{
byte[] buffer = new byte[1000];
int length;
while ((length = inputStream.read(buffer)) > 0)
{
outputStream.write(buffer, 0, length);
}
}
}