Monday, February 9, 2009

Compress and decompreess String object

/**
* This method is used to compress string to byte array
* @author jijo
* @param str
* @return
*/
private static Logger logger = Logger.getLogger(StringUtils.class);
public static byte[] compressString(String str){
byte[] compressedData = null;
if(str != null) {
byte[] input = str.getBytes();

// Create the 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.
// You cannot use an array that's the same size as the orginal because
// there is no guarantee 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) {
e.printStackTrace();
}

// Get the compressed data
compressedData = bos.toByteArray();
}
return compressedData;
}
/**
* This method is used to decompress byte array to normal byte array
* @author jijo
* @param str
* @return
*/
public static byte[] decompressByte(byte compressedData[]){
// Create the decompressor and give it the data to compress
byte[] decompressedData = null;
if(compressedData != null && compressedData.length > 0){
Inflater decompressor = new Inflater();
decompressor.setInput(compressedData);

// Create an expandable byte array to hold the decompressed data
ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.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) {
e.printStackTrace();
}
}
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}

// Get the decompressed data
decompressedData = bos.toByteArray();
}
return decompressedData ;
}

/**
* This method is used to convert byte array to string
* @author jijo
* @param str
* @return
*/

public static String byteArrayToString(byte[] decompress){
String str = null;
try{
str = new String(decompress);
}
catch (Exception e) {
e.printStackTrace();
}
return str;
}

No comments: