Some days ago I needed to pass a XML file as an URL parameter. After some googling I didn’t found anything that┬ásuited┬ámy needs and I ended coding it myself.

Goals

  • Compress a String and encode it with Base64
  • Decompress and decode a Base64 encoded and compressed string.

Decompress method

public static String decompress(String inputStr) throws UnsupportedEncodingException {

		// Base64 decode
		Base64 base64 = new Base64(-1, new byte[0], true);
		byte[] bytes = base64.decode(inputStr.getBytes("UTF-8"));

		// Inflater
		Inflater decompressor = new Inflater();
		decompressor.setInput(bytes);

		// Create an expandable byte array to hold the decompressed data
		ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);

		// Decompress the data
		byte[] buf = new byte[1024];
		while (!decompressor.finished()) {
			try {
				int count = decompressor.inflate(buf);
				bos.write(buf, 0, count);
			} catch (DataFormatException e) {
			}
		}
		try {
			bos.close();
		} catch (IOException e) {
		}

		// Get the decompressed data
		byte[] decompressedData = bos.toByteArray();

		return new String(decompressedData, "UTF-8");
	}

Compress method

	public static String compress(String inputStr) throws UnsupportedEncodingException {
		byte[] input = inputStr.getBytes("UTF-8");

		// Compressor with highest level of compression
		Deflater compressor = new Deflater();
		compressor.setLevel(Deflater.BEST_COMPRESSION);

		// Give the compressor the data to compress
		compressor.setInput(input);
		compressor.finish();

		// Create an expandable byte array to hold the compressed data.
		// It is not necessary that the compressed data will be smaller than
		// the uncompressed data.
		ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);

		// Compress the data
		byte[] buf = new byte[1024];
		while (!compressor.finished()) {
			int count = compressor.deflate(buf);
			bos.write(buf, 0, count);
		}
		try {
			bos.close();
		} catch (IOException e) {
		}

		// Get the compressed data
		byte[] compressedData = bos.toByteArray();

		// Encode Base64
		Base64 base64 = new Base64(-1, new byte[0], true);
		byte[] bytes = base64.encode(compressedData);
		return new String(bytes, "UTF-8");
	}