Friday 18 March 2011

Compressing java string

Here are 2 static methods to do compression and decompression
private static String compressString(String myString) {
byte[] myByte = myString.getBytes();

System.out.println(“Original String is :+ myString);

// Compression level of best compression
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);

// Give the Compressor the input data to compress

compressor.setInput(myByte);
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(myByte.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 (Exception e) {
e.printStackTrace();
}

// Get the compressed data
byte[] compressedMyByte = bos.toByteArray();
String compressedMyString = new String(compressedMyByte);

return compressedMyString;
}

private static String deCompressString(String compressedMyString) {

Inflater decompressor = new Inflater();
byte[] buf = new byte[1024];
byte[] compressedMyByte = compressedMyString.getBytes();
decompressor.setInput(compressedMyByte);

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

// Decompress the data
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 (Exception e) {
e.printStackTrace();
}

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

String decompressedMyString = new String(decompressedMyByte);

return decompressedMyString;

}

No comments:

Post a Comment