How can I compress/uncompress a long string or a file (of any type)?
Created May 4, 2012
John Mitchell Check out the java.util.zip.GZIPInputStream and java.util.zip.GZIPOutputStream classes. The following demonstrates compressing a file:
import java.io.*; import java.net.*; import java.util.zip.*; public class CompressIt { public static void main(String[] args) { if (args.length !=1) { displayUsage(); System.exit(-1); } else { String filename = args[0]; compressIt(filename); } } private static void displayUsage() { System.err.println( "Usage: java CompressIt filename"); } private static void compressIt(String filename) { try { File file = new File(filename); // small files only int length = (int) file.length(); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); ByteArrayOutputStream baos = new ByteArrayOutputStream(length); GZIPOutputStream gos = new GZIPOutputStream(baos); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { gos.write(buffer, 0, bytesRead); } bis.close(); gos.close(); System.out.println("Input Length: " + length); System.out.println("Output Length: " + baos.size()); } catch (FileNotFoundException e) { System.err.println("Invalid Filename"); } catch (IOException e) { System.err.println("I/O Exception in transit"); } } }
The following table demonstrates the compression results. Depending upon the type of input, the results can vary considerably.
File | Size | Compressed |
---|---|---|
CompressIt.java | 1,330 | 540 |
(AWT) Component.java | 133,742 | 26,042 |
Symantec JIT - symcjit.dll | 419,840 | 193,501 |
Java 2 SDK, version 1.2.2 - src.jar | 17,288,462 | 3,252,177 |