Compress a String Using Deflater

Compress a String Using Deflater best compression algorithm.

Javadoc available at https://www.javatapas.com/docs/javatapas/string/CompressString.html


public static String compressString(String inStr) {

	byte[] inBytes = inStr.getBytes();

	Deflater compressor = new Deflater();
	compressor.setLevel(Deflater.BEST_COMPRESSION);
	compressor.setInput(inBytes);
	compressor.finish();

	ByteArrayOutputStream bos = new ByteArrayOutputStream(inBytes.length);

	byte[] buf = new byte[1024];
	while (!compressor.finished()) {
		int count = compressor.deflate(buf);
		bos.write(buf, 0, count);
	}

	try {bos.close();}
	catch (IOException e) {e.printStackTrace();}

	byte[] compressedBytes = bos.toByteArray();
	String compressedStr = new String(compressedBytes);

	return compressedStr;
}