De Daniel Pecos
- Funciones para comprimir/descomprimir cadenas con GZIP
public static byte[] compressString(String str) {
byte[] compressedStr = null;
if (str != null && str != "") {
GZIPOutputStream gzos = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
gzos = new GZIPOutputStream(baos);
gzos.write(str.getBytes());
gzos.flush();
gzos.close();
compressedStr = baos.toByteArray();
} catch (IOException ioe) {
System.out.println("Error I/O en la compresion");
try {
gzos.close();
} catch (IOException io) {
System.out.println("Error I/O al cerrar el stream");
}
}
}
return compressedStr;
}
public static String uncompressString(byte [] compressedStr) {
String str = null;
if (compressedStr != null && compressedStr.length > 0) {
GZIPInputStream gzis = null;
try {
ByteArrayInputStream bais = new ByteArrayInputStream(compressedStr);
gzis = new GZIPInputStream(bais);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int size = 0;
while ((size = gzis.read(buffer)) > 0) {
baos.write(buffer, 0, size);
}
gzis.close();
baos.close();
str = new String (baos.toByteArray());
} catch (IOException ioe) {
System.out.println("Error I/O en la descompresion");
try {
gzis.close();
} catch (IOException io) {
System.out.println("Error I/O al cerrar el stream");
}
}
}
return str;
}